【问题标题】:Cannot find the file specified when using subprocess.call('dir') in Python在 Python 中使用 subprocess.call('dir') 时找不到指定的文件
【发布时间】:2018-09-17 11:42:00
【问题描述】:

我在 Windows 10 上运行以下 Python 文件:

import subprocess

subprocess.call("dir")

但我收到以下错误:

  File "A:/python-tests/subprocess_test.py", line 10, in <module>
    subprocess.call(["dir"])

  File "A:\anaconda\lib\subprocess.py", line 267, in call
    with Popen(*popenargs, **kwargs) as p:

  File "A:\anaconda\lib\site-packages\spyder\utils\site\sitecustomize.py", line 210, in __init__
    super(SubprocessPopen, self).__init__(*args, **kwargs)

  File "A:\anaconda\lib\subprocess.py", line 709, in __init__
    restore_signals, start_new_session)

  File "A:\anaconda\lib\subprocess.py", line 997, in _execute_child
    startupinfo)

FileNotFoundError: [WinError 2] The system cannot find the file specified

请注意,我在这里仅使用dir 作为示例。我实际上想运行一个更复杂的命令,但在这种情况下我也会遇到同样的错误。

注意我没有使用shell=True,所以这个问题的答案不适用:Cannot find the file specified when using subprocess.call('dir', shell=True) in Python

这是subprocess.py的第997行:

hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
                                         # no special security
                                         None, None,
                                         int(not close_fds),
                                         creationflags,
                                         env,
                                         os.fspath(cwd) if cwd is not None else None,
                                         startupinfo)

当我运行调试器检查传递给 CreateProcess 的参数时,我注意到 executableNone。这正常吗?

【问题讨论】:

    标签: python-3.x windows-10


    【解决方案1】:

    dir 是在 cmd.exe 中实现的命令,因此没有 dir.exe windows 可执行文件。必须通过cmd调用命令。

    subprocess.call(['cmd', '/c', 'dir'])
    

    【讨论】:

      【解决方案2】:

      必须在调用dir 时设置shell=True,因为dir 不是可执行文件(没有像dir.exe 这样的东西)。 dir 是一个 internal command,它是用 cmd.exe 加载的。

      你可以从documentation看到:

      在带有shell=True 的 Windows 上,COMSPEC 环境变量指定 默认外壳。唯一需要指定shell=True on Windows 是您希望执行的命令内置于 外壳(例如 dir 或复制)。您不需要shell=True 来运行批处理 文件或基于控制台的可执行文件。

      【讨论】:

        猜你喜欢
        • 2013-12-18
        • 2011-03-02
        • 1970-01-01
        • 2017-02-10
        • 2022-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多