是python subprocess.Popen接受路径中的空格吗?

问题描述 投票:6回答:3

我有一个简单的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可以如何处理空间路径并且没有逃脱?

python createprocess
3个回答
3
投票

需要转义带空格的路径。最简单的方法是将命令设置为列表,添加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)

2
投票

考虑一下:

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, ...)

1
投票

对于任何偶然发现此帖子寻找解决方案的人来说,将可执行文件封装在引号中可以在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)
© www.soinside.com 2019 - 2024. All rights reserved.