Python:“FileNotFoundError"在所有子流程调用上 [英] Python: "FileNotFoundError" on all Subprocess calls
问题描述
使用 Windows 7、Python 3.5.1:
Using 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 和 subproccess.Popen.无论使用什么命令都会发生同样的错误:
This error occurs with all subprocess calls, such as subprocess.run, subprocess.call, and subproccess.Popen. The same error happens regardless of what command is used:
subprocess.check_output(['['D:\path\to\exe\program.exe', 'argument'])
FileNotFoundError: [WinError 2] The system cannot find the file specified
据我所知,这个错误通常发生在命令尝试执行一个不存在的路径时,但我无法确定为什么会在这些情况下发生.
As far as I can tell, this error usually occurs when the command tries to execute a nonexistent path, but I can't determine why it would occur in these cases.
推荐答案
您需要包含可执行文件的完整路径.例如,
You need to include the full path to your executable. E.g.,
import subprocess
subprocess.check_output(['/bin/echo', 'hello'])
(不过不确定它在 Windows 上的确切位置.)
(Not sure precisely where it is on Windows, though.)
注意:使用 shell=True
也会使它起作用,但我不建议这样解决它,因为 (1) 你的 PATH
解析将有效是一个副作用(你将在运行时对 PATH
的值有一个隐藏的依赖),并且 (2) 有 安全问题.
Note: Using shell=True
will also make it happen to work, but I don't recommend solving it that way because (1) your PATH
resolution will effectively be a side-effect (you'll have a hidden dependency on the value of PATH
at runtime), and (2) there are security concerns.
这篇关于Python:“FileNotFoundError"在所有子流程调用上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!