Python的子进程。Popen接受路径中的空格吗?

问题描述 投票:9回答:4

我有一个简单的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,我在其中的only上遇到了错误。

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
4个回答
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, ...)

2
投票

对于偶然发现这篇文章的人,寻求解决方案,将可执行文件封装在引号中可以在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)

0
投票

这是我发现可用于Windows的内容:

以下任一语句将使用指定的程序打开指定的文件:

subprocess.run('start EXCEL.exe "%s"' %cmd_path, shell=True)
os.system('start EXCEL.exe "%s"' %cmd_path)

不幸的是,subprocess.run不适用于可迭代的参数。以下对我来说没有用:

subprocess.call(['start','EXCEL.EXE', f'"%s"'%save_path])
subprocess.run(['start','EXCEL.EXE', f"%s"%save_path])
os.system('start EXCEL.EXE ' + f"%s"%save_path)
© www.soinside.com 2019 - 2024. All rights reserved.