Does Python's subprocess.Popen accept spaces in paths?

erkfel picture erkfel · Sep 4, 2014 · Viewed 18.8k times · Source

I have a simple Python script:

log("Running command: " + str(cmd))
process = subprocess.Popen(
    cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, 
    stdin=subprocess.PIPE, close_fds=close_fds)

I'm executing it on Windows on the same python version 2.6.1, but on different VMs. One is Windows Server 2008 Enterprise, the second one it Windows Server Enterprise and I got error on only one of them.

The log from Windows Server Enterprise:

Running command: C:\Program File\MyProgram\program.exe "parameters"
Error: 'C:\\Program' is not recognized as an internal or external command

The log from Windows Server 2008 Enterprise:

Running command: C:\Program File\MyProgram\program.exe "parameters"
...

The error happens only for one environment. I know that the path should be escaped, but how is that possible that the subprocess.Popen could handle the path with space and without escaping?

Answer

tdelaney picture tdelaney · Sep 4, 2014

Paths with spaces need to be escaped. The easiest way to do this is to setup the command as a list, add shell=True and let python do the escaping for you:

import subprocess
cmd = [r"C:\Program File\MyProgram\program.exe", "param1", "param2"]
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,stdin=subprocess.PIPE, close_fds=close_fds)