'Errno 2 no such file or directory' 使用子处理模块 Popen 命令时目录路径中出现空格问题

问题描述 投票:0回答:1

我有以下代码,可让我使用子处理库运行 .py 文件

代码

import subprocess
process = subprocess.Popen('python C:/Users/Example User/Projects/file.py', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

output, error = process.communicate()
print('output')
print(output)
print('error')
print(error)

问题

我遇到的问题是没有输出,并且打印错误显示以下消息:“c:/example/python/directory/python.exe 无法打开文件 'C:\Users\Example' : [Errno 2] 没有这样的文件或目录 “(这是我在终端中得到的完整错误)

我认为这个问题可能与存在空格有关,因为目录的其余部分没有显示,但我可能完全错了。 如果我的当前目录中有该文件,那么只要我不向其传递完整路径地址,代码就可以工作(即,如果我只给出 Popen ('python file.py' 代码执行正常)

我尝试过的事情

我尝试过使用(双反斜杠)\、+' '、//、/、单\、 我无法更改工作计算机上的主目录,但我尝试在个人电脑上使用它并且它可以工作(我的目录中没有空格)。 https://docs.python.org/3/library/subprocess.html 文档确实提到它应该像在 shell 中一样格式化。

如果 args 是字符串,则该字符串指定通过 shell 执行的命令。这意味着字符串的格式必须与在 shell 提示符下键入时完全相同。例如,这包括引用或反斜杠转义其中包含空格的文件名。如果 args 是一个序列,则第一项指定命令字符串,任何其他项将被视为 shell 本身的附加参数。

任何帮助和所有建议将不胜感激,或者如果我可以做任何事情让问题更清楚

python python-3.x subprocess ascii
1个回答
0
投票

你的论点分为两部分。

process = subprocess.Popen('python \"C:/Users/Example User/Projects/file.py\"', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
© www.soinside.com 2019 - 2024. All rights reserved.