我有一个简单的Python脚本:
log("Running command: " + str(cmd))
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, close_fds=close_fds)
我在Windows上在相同的python版本2.6.1上执行它,但在不同的VM上。一个是Windows Server 2008 Enterprise,第二个是Windows Server Enterprise,我只有一个错误。
Windows Server Enterprise中的日志:
Running command: C:\Program File\MyProgram\program.exe "parameters"
Error: 'C:\\Program' is not recognized as an internal or external command
Windows Server 2008 Enterprise中的日志:
Running command: C:\Program File\MyProgram\program.exe "parameters"
...
该错误仅发生在一个环境中。我知道路径应该被逃脱,但是subprocess.Popen
可以如何处理空间路径并且没有逃脱?
需要转义带空格的路径。最简单的方法是将命令设置为列表,添加shell = True并让python为您执行转义:
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)
考虑一下:
command = "C:\Path argument\or\path"
你如何区分可执行的C:\Path
与参数argument\or\path
和命令path
位于C:\Path\ argument\or
?但是,如果将列表而不是字符串传递给Popen
,则意图是明确的:
command = ["C:\Path argument\or\path"]
proc = Popen(command, ...)
对于任何偶然发现此帖子寻找解决方案的人来说,将可执行文件封装在引号中可以在Windows上工作,并且用'\'替换'''在bash(Linux / MacOS)中用于Popen shell命令。
这对我有用:
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)