Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subprocess with a variable that contains a whitespace (path)

Just started Python again and now I'm already stuck on the following...

I'm trying to use subprocess.Popen with a variable with a whitespace in it (a Windows path).

Doing a print on the variable the variable seems to work fine. But when using the variable in subprocess.Popen, the variable is cut off by the first whitespace.

Below a part of the script (the variable 'image_file' contains the Windows Path(s) with spaces)

def start_phone(image_file):
    cmd = tar_exe + " -tf "+ image_file
    print (cmd)
    subprocess.Popen(cmd, shell=True)

How can I use subprocess with a variable with whitespaces (path) in it?

like image 935
Vroluk Avatar asked Oct 21 '25 05:10

Vroluk


2 Answers

You can either put double quotes around each argument with potential white spaces in it:

cmd = f'"{tar_exe}" -tf "{image_file}"'
subprocess.Popen(cmd, shell=True)

or don't use shell=True and instead put arguments in a list:

subprocess.Popen([tar_exe, '-tf', image_file])
like image 161
blhsing Avatar answered Oct 24 '25 17:10

blhsing


If you take a look at the subprocess documentation you'll see that arguments must be provided to subprocess commands in the form of a list, so your code sample should look like

def start_phone(image_file):
    subprocess.Popen([tar_exe, "-tf", image_file])
like image 40
Bitsplease Avatar answered Oct 24 '25 18:10

Bitsplease



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!