python - 在Python中使用子进程时出现回溯错误

标签 python windows subprocess

当尝试使用 subprocess.check_output 时,我不断收到此回溯错误:

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    subprocess.check_output(["echo", "Hello World!"])
  File "C:\Python27\lib\subprocess.py", line 537, in check_output
    process = Popen(stdout=PIPE, *popenargs, **kwargs)
  File "C:\Python27\lib\subprocess.py", line 679, in __init__
    errread, errwrite)
  File "C:\Python27\lib\subprocess.py", line 896, in _execute_child
    startupinfo)
WindowsError: [Error 2] The system cannot find the file specified

当我尝试时甚至会发生这种情况:

>>>subprocess.check_output(["echo", "Hello World!"])

这恰好是文档中的示例。

最佳答案

由于 ECHO 内置于 Windows cmd shell 中,因此您无法像调用可执行文件那样直接从 Python 调用它(或者像调用可执行文件一样直接调用它)在 Linux 上调用它)。

即这应该适用于您的系统:

import subprocess
subprocess.check_output(['notepad'])

因为 notepad.exe 是可执行文件。但在 Windows 中,echo 只能从 shell 提示符内部调用,因此使其工作的简单方法是使用 shell=True。为了忠实于你的代码,我必须写

subprocess.check_output(['echo', 'hello world'], shell=True) # Still not perfect

(这,在 subprocess.py 第 924 行的条件之后会将 args 扩展为整行 'C:\\Windows\\system32\\cmd.exe/c "echo "hello world""',从而调用 cmd shell 并使用 shell 的 echo 命令)

但是,正如 @J.F.Sebastian 善意指出的那样,for portability a string, and not a list, should be used to pass arguments when using shell=True (检查那里的问题链接)。因此,在您的情况下调用 subprocess.check_output 的最佳方法是:

subprocess.check_output('echo "hello world"', shell=True)

args 字符串又是正确的,'C:\\Windows\\system32\\cmd.exe/c "echo "hello world""'并且您的代码更加可移植。

docs说:

"On Windows with shell=True, the COMSPEC environment variable specifies the default shell. The only time you need to specify shell=True on Windows is when the command you wish to execute is built into the shell (e.g. dir or copy). You do not need shell=True to run a batch file or console-based executable.

Warning: Passing shell=True can be a security hazard if combined with untrusted input. See the warning under Frequently Used Arguments for details. "

关于python - 在Python中使用子进程时出现回溯错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28161167/

相关文章:

python - Python 2 中的 TFS Rest Api 授权问题

ruby-on-rails - Windows 版 Ruby on Rails 2.0 入门

python - 如何将错误消息从 shell 脚本传递到 Python 脚本?

python - 为什么如果使用列表理解该函数不会更新列表,但在使用 for 循环时会更新列表

python - 根据另一列中设置的金额向 pandas 列添加零

python - “NoneType”对象无法使用装饰器类调用

c - 当我调用 IDirect3DDevice9::Reset 时会发送哪些消息

c++ - Windows GTest EXPECT_STREQ : error: no matching function for call to 'CmpHelperSTREQ'

python-3.x - 使用 asyncio 等待子进程的结果

python - Python子进程中的curl问题