【问题标题】:Why won't my python subprocess code work? [duplicate]为什么我的 python 子进程代码不起作用? [复制]
【发布时间】:2013-05-08 19:17:34
【问题描述】:
from subprocess import *

test = subprocess.Popen('ls')
print test

当我尝试运行这个简单的代码时,我收到一个错误窗口:

WindowsError: [Error 2] The system cannot find the file specified

我不知道为什么我不能让这个简单的代码工作,这很令人沮丧,任何帮助将不胜感激!

【问题讨论】:

  • 您的路径中有“ls.exe”吗?等等,你用的是什么操作系统?
  • 是的,那如何让Windows系统知道ls命令呢?
  • @user2371187 如果你想要一个文件列表,使用os.listdir()会更简单。
  • windows 没有 ls(除非 powershell/mingw32);它使用dir

标签: python windows subprocess windowserror


【解决方案1】:

您似乎想要存储来自subprocess.Popen() 调用的输出。
如需更多信息,请参阅Subprocess - Popen.communicate(input=None)

>>> import subprocess
>>> test = subprocess.Popen('ls', stdout=subprocess.PIPE)
>>> out, err = test.communicate()
>>> print out
fizzbuzz.py
foo.py
[..]

但是,Windows shell (cmd.exe) 没有 ls 命令,但还有另外两种选择:

使用os.listdir() - 这应该是首选方法,因为它更容易使用:

>>> import os
>>> os.listdir("C:\Python27")
['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe
', 'pythonw.exe', 'README.txt', 'tcl', 'Tools', 'w9xpopen.exe']

使用 Powershell - 默认安装在较新版本的 Windows (>= Windows 7) 上:

>>> import subprocess
>>> test = subprocess.Popen(['powershell', '/C', 'ls'], stdout=subprocess.PIPE)
>>> out, err = test.communicate()
>>> print out


    Directory: C:\Python27


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----        14.05.2013     16:00            DLLs
d----        14.05.2013     16:01            Doc
[..]

使用 cmd.exe 的 Shell 命令是这样的:

test = subprocess.Popen(['cmd', '/C', 'ipconfig'], stdout=subprocess.PIPE)

欲了解更多信息,请参阅:
The ever useful and neat subprocess module - Launch commands in a terminal emulator - Windows


注意事项:

【讨论】:

  • 我仍然遇到同样的 windows 错误.. :(
  • @user2371187 我在 Linux 上运行 Python,但你能试试我最后的编辑吗? Popen('cmd', '/C', 'ls')?
  • @timss 默认情况下,Windows 上没有 ls 二进制文件,cmd.exe 中也没有该名称的命令。 powershell.exe 中有一个,尽管它的输出与 Unix 的 ls 有很大不同。 os.listdir() 可能是在 Windows 上复制 ls 的最简单方法。
  • @Aya 哦,当然。自从我使用 cmd.exe 以来已经有一段时间了。我会更新我的答案。
  • @timss FWIW, subprocess.Popen(['powershell', '/C', 'ls']) 可以,但是解析输出会很麻烦。
【解决方案2】:

同意 timss; Windows 没有ls 命令。如果您想在 Windows 上使用 ls 之类的目录列表,请使用 dir /B 表示单列或使用 dir /w /B 表示多列。或者只使用os.listdir。如果您使用dir,则必须使用subprocess.Popen(['dir', '/b'], shell=True) 启动子进程。如果要存储输出,请使用subprocess.Popen(['dir', '/b'], shell=True, stdout=subprocess.PIPE)。而且,我使用shell=True 的原因是,因为dir 是一个内部DOS 命令,所以必须使用shell 来调用它。 /b 去除标题,/w 强制多列输出。

【讨论】:

    猜你喜欢
    • 2012-12-02
    • 2013-06-20
    • 2020-04-20
    • 2011-05-31
    • 2023-02-05
    • 1970-01-01
    • 2014-09-26
    • 2021-10-28
    • 2017-09-19
    相关资源
    最近更新 更多