python subprocess.Popen是否在路径中接受空间?

erk*_*fel 8 python createprocess

我有一个简单的Python脚本:

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

我在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
Run Code Online (Sandbox Code Playgroud)

Windows Server 2008 Enterprise的日志:

Running command: C:\Program File\MyProgram\program.exe "parameters"
...
Run Code Online (Sandbox Code Playgroud)

该错误仅在一种环境下发生。我知道该路径应该转义,但是,如何有可能在subprocess.Popen没有空间的情况下处理该路径?

tde*_*ney 5

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

  • @AlexanderTronchin-James - 马车?如果 _shell=True_ 导致挂起,这是我第一次听说。_shell=True_ 确实存在命令注入的风险,因此不建议在任何地方使用它,但在许多情况下合理使用它。例如构建系统。 (3认同)

归档时间:

查看次数:

12503 次

最近记录:

6 年,10 月 前