python - 找不到文件错误 : [WinError 2] The system can't find the specified file

标签 python python-3.x subprocess

我目前正在学习如何使用模块 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'))

在书中他们说这段代码应该在屏幕上打印“你好”,但由于某些原因,它没有。

这里有什么问题?如果对您有帮助,我目前使用的是 python 3.4.3。

最佳答案

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

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

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

关于python - 找不到文件错误 : [WinError 2] The system can't find the specified file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36249622/

相关文章:

python - 如何使用 Python 获取存储库分支列表

python - 在windows上通过python调用使用linux子系统编译的程序

python - imaplib - 在 PC 上工作但在服务器上不起作用?

python - Eclipse中打开各种main.py文件而不新建项目

python - 移动表单上的按钮

python-3.x - 在 jupyter notebook 中将自定义 jars 添加到 pyspark

python - 如何在列表中选择随机位置,翻转位,然后浏览下一个项目

python - 以编程方式将 kml 转换为图像

python - Emacs 中的 bpython

python - 为什么 pytesseract 抛出 WinError 6?