在 Python 中使用 subprocess.call('dir') 时找不到指定的文件

use*_*r89 2 python-3.x windows-10

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

import subprocess

subprocess.call("dir")
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误:

  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
Run Code Online (Sandbox Code Playgroud)

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

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

这是第 997 行subprocess.py:

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)
Run Code Online (Sandbox Code Playgroud)

当我运行调试器来检查传递给 CreateProcess 的参数时,我注意到它executable是None. 这是正常的吗?

abc*_*ccd 6

您必须shell=True在调用时进行设置dir,因为dir它不是可执行文件(没有 dir.exe 这样的东西)。dir是与 cmd.exe 一起加载的内部命令。

正如您从文档中看到的:

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


Pri*_*usa 5

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

subprocess.call(['cmd', '/c', 'dir'])
Run Code Online (Sandbox Code Playgroud)