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

Sri*_*Sri 88 python path python-3.x

我收到以下错误:

WindowsError: [Error 2] The system cannot find the file specified
Run Code Online (Sandbox Code Playgroud)

我的代码是:

subprocess.call(["<<executable file found in PATH>>"])
Run Code Online (Sandbox Code Playgroud)

Windows 7,64位.Python 3.x最新,稳定.

有任何想法吗?

谢谢,

小智 158

当命令是内置shell时,在调用中添加'shell = True'.

例如,dir您可以输入:

import subprocess
subprocess.call('dir', shell=True)
Run Code Online (Sandbox Code Playgroud)

引用文档:

您需要在Windows上指定shell = True的唯一时间是您希望执行的命令是否内置到shell中(例如dir或copy).您不需要shell = True来运行批处理文件或基于控制台的可执行文件.

  • 那是因为没有名为`dir.exe`的可执行文件,而*nix中有一个`/ bin/ls`.`dir`由_CMD.EXE实现,就像`cd`由_bash_实现一样. (14认同)
  • @nueverest仅当从外部输入_构造_the命令字符串时 (11认同)

pto*_*ato 23

在Windows上,我相信除非你通过subprocess,PATH否则模块不会查看shell=True.但是,shell=True如果您传递可能来自程序外部的参数,则可能存在安全风险.为了subprocess能够找到正确的可执行文件,您可以使用shutil.which.假设您的可执行文件PATH被命名为frob:

subprocess.call([shutil.which('frob'), arg1, arg2])
Run Code Online (Sandbox Code Playgroud)

(这适用于Python 3.3及更高版本.)

  • 任何python 2选项? (4认同)

小智 14

在Windows上,您必须通过cmd.exe进行调用.正如Apalala所提到的,Windows命令在cmd.exe中实现,而不是作为单独的可执行文件实现.

例如

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

/ c告诉cmd运行follow命令

这比使用shell = True更安全,它允许shell注入.

  • @Moondra,如果我理解正确,请尝试`/ k`而不是`/ c`.在命令行输入`cmd /?`以获取详细信息. (2认同)