Windows无法在subprocess.call()中找到文件

138 投票
7 回答
139964 浏览
提问于 2025-04-15 23:50

我遇到了以下错误:

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

我的代码是:

subprocess.call(["<<executable file found in PATH>>"])

我使用的是Windows 7,64位系统。Python 3.x的最新稳定版本。

有什么建议吗?

谢谢,

7 个回答

27

在Windows系统上,你需要通过cmd.exe来执行命令。正如Apalala提到的,Windows的命令是在cmd.exe里实现的,而不是作为单独的程序。

比如:

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

/c是告诉cmd去运行后面的命令。

这样做比使用shell=True更安全,因为后者可能会导致安全问题,比如被恶意代码注入。

50

在Windows系统上,我认为 subprocess模块在没有设置 shell=True 的情况下不会查找 PATH,因为它在后台使用了 CreateProcess() 不过,使用 shell=True 可能会带来安全风险,特别是当你传入的参数可能来自程序外部时。为了让 subprocess 仍然能够找到正确的可执行文件,你可以使用 shutil.which。假设你在 PATH 中的可执行文件叫做 frob

subprocess.call([shutil.which('frob'), arg1, arg2])

(这个方法在Python 3.3及以上版本中有效。)

223

当你要执行的命令是 shell 内置的命令时,需要在调用时加上 shell=True

比如说,如果你想使用 dir 命令,你可以这样输入:

import subprocess
subprocess.call('dir', shell=True)

根据 文档的说明:

在 Windows 系统上,只有当你想执行的命令是 shell 内置的(比如 dircopy)时,才需要指定 shell=True。如果你要运行的是批处理文件或控制台可执行文件,就不需要加 shell=True

撰写回答