Python:所有Subprocess调用上的“FileNotFoundError”

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

使用Windows 7,Python 3.5.1:

import subprocess
subprocess.check_output(['echo', 'hello'])

提出错误:

Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
    subprocess.check_output(['echo', 'hello'])
File "D:\Programs\Python 3.5.1\lib\subprocess.py", line 629, in check_output
    **kwargs).stdout
File "D:\Programs\Python 3.5.1\lib\subprocess.py", line 696, in run
    with Popen(*popenargs, **kwargs) as process:
File "D:\Programs\Python 3.5.1\lib\subprocess.py", line 950, in __init__
    restore_signals, start_new_session)
File "D:\Programs\Python 3.5.1\lib\subprocess.py", line 1220, in _execute_child
    startupinfo)

FileNotFoundError: [WinError 2] The system cannot find the file specified

所有子进程调用都会发生此错误,例如subprocess.run,subprocess.call和subprocess.Popen。无论使用什么命令,都会发生相同的错误:

subprocess.check_output(['['D:\path\to\exe\program.exe', 'argument'])
FileNotFoundError: [WinError 2] The system cannot find the file specified

据我所知,当命令试图执行不存在的路径时,通常会发生此错误,但我无法确定在这些情况下会发生的原因。

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

您需要包含可执行文件的完整路径。例如。,

import subprocess
subprocess.check_output(['/bin/echo', 'hello'])

(但不确定它在Windows上的确切位置。)

注意:使用shell=True也会使它碰巧工作,但我不建议那样解决它,因为(1)你的PATH分辨率实际上是一个副作用(你将隐藏依赖于PATH的值运行时),和(2)有security concerns

© www.soinside.com 2019 - 2024. All rights reserved.