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?
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])
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With