【问题标题】:FileNotFoundError: [WinError 2] The system can't find the specified fileFileNotFoundError: [WinError 2] 系统找不到指定的文件
【发布时间】:2016-03-27 16:14:37
【问题描述】:

我目前正在学习如何使用模块subprocess,我刚刚开始阅读我的新书。立即,我收到一条我不明白的错误消息。

Traceback (most recent call last):
  File "D:/me/Python/subprocess.py", line 3, in <module>
    proc = subprocess.Popen(['echo', 'Hello there'], stdout=subprocess.PIPE)
  File "C:\Python34\lib\subprocess.py", line 859, in __init__
    restore_signals, start_new_session)
  File "C:\Python34\lib\subprocess.py", line 1112, in _execute_child
    startupinfo)
FileNotFoundError: [WinError 2] The system can't find the specified file

我无法弄清楚这里出了什么问题

import subprocess

proc = subprocess.Popen(['echo', 'Hello there'], stdout=subprocess.PIPE)
out, err = proc.communicate()
print(out.decode('utf-8'))

在书中他们说这段代码应该在屏幕上打印“Hello there”,但出于某种原因,它没有。

这里有什么问题?我目前正在使用 python 3.4.3,如果对你有帮助的话。

【问题讨论】:

    标签: python python-3.x subprocess


    【解决方案1】:

    echo 不是可以执行的程序,但它是 Windows 命令行解释器 cmd.exe 中可用的 shell 命令。

    为了执行shell命令,你需要将shell=True传递给Popen

    proc = subprocess.Popen(['echo', 'Hello there'], stdout=subprocess.PIPE, shell=True)
    #                                                                        ^^^^^^^^^^
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-21
      • 1970-01-01
      • 1970-01-01
      • 2020-01-02
      • 1970-01-01
      • 2017-08-01
      • 2019-07-29
      • 1970-01-01
      相关资源
      最近更新 更多