Is python subprocess.Popen accept space in path?

99封情书 提交于 2019-12-23 07:52:44

问题


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?


回答1:


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)



回答2:


Consider this:

command = "C:\Path argument\or\path"

How do you differentiate between an executable C:\Path with an argument argument\or\path and a command path located at C:\Path\ argument\or? If you pass an list instead of a string to Popen however, the intent is unambiguous:

command = ["C:\Path argument\or\path"]
proc = Popen(command, ...)



回答3:


For anybody that stumbles upon this post looking for a solution to this, encapsulating the executable in quotes works on Windows and replacing ' ' with '\ ' works in bash (Linux/MacOS) for Popen shell commands.

Here's what worked for me:

from subprocess import Popen
cmd = '/path/to/some executable with spaces'
# Execute in Windows shell:
Popen(r'"{}"'.format(cmd), shell=True)
# Execute in bash shell:
Popen(cmd.replace(' ', '\ '), shell=True)


来源:https://stackoverflow.com/questions/25655173/is-python-subprocess-popen-accept-space-in-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!