4

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?

3 Answers 3

6

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]) 
Sign up to request clarification or add additional context in comments.

Comments

1

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]) 

Comments

0

Use the shlex.quote() for handling the whitespaces for subprocess.Popen(). This must be used with shell=False for avoiding any command injection which is a possibility.

1 Comment

It works only on linux

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.