【问题标题】:Error during subprocess calling ls子进程调用ls期间出错
【发布时间】:2014-09-25 07:00:11
【问题描述】:

知道错误是什么意思吗?

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    subprocess.call(["ls", "-l"])
  File "D:\Python27\lib\subprocess.py", line 522, in call
    return Popen(*popenargs, **kwargs).wait()
  File "D:\Python27\lib\subprocess.py", line 710, in __init__
    errread, errwrite)
  File "D:\Python27\lib\subprocess.py", line 958, in _execute_child
    startupinfo)
WindowsError: [Error 2] The system cannot find the file specified

【问题讨论】:

    标签: python windows subprocess ls dir


    【解决方案1】:

    您正尝试在 Windows 上执行 ls -l 命令。 ls 仅适用于基于 Unix 的系统。

    subprocess.call(["ls", "-l"])
    

    如果您使用的是 Windows,请尝试

    subprocess.call(["dir"])
    

    改为。

    或者,您可以尝试类似Cygwin

    【讨论】:

    • 我确实尝试过您的代码“subprocess.call(["dir"])”,但它仍然显示相同的错误(顺便说一下,我在 Windows 上)
    • 我需要做一个PATH吗?
    • 根据 subprocess.call 的实现方式,它可能需要是“cmd /c dir”,因为 dir 是内置的,而不是可执行文件。但是使用 Python 自己的文件管理功能会更明智。
    【解决方案2】:

    您在没有ls 的Windows 上调用ls 命令。您可以从http://gnuwin32.sourceforge.net/packages/coreutils.htm 获取 Windows 的 ls 端口并将其安装的 bin dir 添加到您的 windows PATH (或在您的 python 脚本运行时将其添加到 PATH。如果您不知道如何执行此操作,请分别查看thisthis 问题)。

    dir 是 windows 的等价物,但与ls 相比,它会打印不同格式的输出,并且推测此调用是为了从目录中获取某种信息。在 python 中有更好的方法来做到这一点。如果您可以识别它试图获取的信息(例如权限位),那么您可能能够编写一个纯 python 版本(或为执行此操作的 Windows 找到等效的 python sn-p)而不依赖于外部命令。

    有趣的是,subprocess.call() 只是运行命令并返回错误代码。 ls 本身只是打印信息,所以如果这是意图(只是为了在控制台中向用户显示目录的内容),那么您可以将其替换为对 dir 的调用。有时,您需要提供shell=True 作为参数,具体取决于您调用的命令。不过请注意文档中的warning。如果它试图提取信息,它可能想要进行subprocess.Popen()subprocress.check_output() 样式调用,您实际上可以在其中使用被调用程序的输出。

    例如,如果只是获取目录中的文件/目录列表和/或它们的时间戳,那么这是获取这些信息的一种非常迂回的方式,它们都可以在 python 本身中完成例如os.walk()os.fstat() 和 Python3 中的 pathlib 是获取目录中文件信息的一些方法。

    【讨论】:

      猜你喜欢
      • 2021-04-30
      • 2014-05-08
      • 1970-01-01
      • 1970-01-01
      • 2017-02-19
      • 1970-01-01
      • 2014-10-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多