[英]subprocess.call() in windows 10 returns an error that it can't find the file
[英]Windows can't find the file on subprocess.call()
我收到以下错误:
WindowsError: [Error 2] The system cannot find the file specified
我的代码是:
subprocess.call(["<<executable file found in PATH>>"])
Windows 7,64 位。 Python 3.x 最新,稳定。
有任何想法吗?
谢谢,
当命令是内置shell=True
,在调用中添加shell=True
。
例如,对于dir
您可以输入:
import subprocess
subprocess.call('dir', shell=True)
从文档中引用:
在 Windows 上您唯一需要指定
shell=True
时间是您希望执行的命令已内置到 shell 中(例如dir或copy )。 您不需要shell=True
来运行批处理文件或基于控制台的可执行文件。
在 Windows 上,我相信subprocess
模块不会在PATH
查找,除非您传递shell=True
因为它在幕后使用CreateProcess()
。 但是,如果您传递的参数可能来自程序外部,则shell=True
可能存在安全风险。 为了使subprocess
shutil.which
仍然能够找到正确的可执行文件,您可以使用shutil.which
。 假设PATH
的可执行文件名为frob
:
subprocess.call([shutil.which('frob'), arg1, arg2])
(这适用于 Python 3.3 及更高版本。)
在 Windows 上,您必须通过 cmd.exe 调用。 正如 Apalala 所提到的,Windows 命令是在 cmd.exe 中实现的,而不是作为单独的可执行文件。
例如
subprocess.call(['cmd', '/c', 'dir'])
/c 告诉 cmd 运行以下命令
这比使用 shell=True 更安全,后者允许 shell 注入。
如果您使用的是 powershell,则其中将是subprocess.call(['powershell','-command','dir'])
。 Powershell 支持大部分 POSIX 命令
经过多次摸索,我发现在 64 位机器上运行 32 位版本的 python 时运行位于 C:\\Windows\\System32\\ 中的文件是一个潜在问题,因为 Windows 试图超越该进程,并且将对 C:\\Windows\\System32 的调用重定向到 C:\\Windows\\SysWOW64。
我在这里找到了一个如何解决这个问题的例子: http : //code.activestate.com/recipes/578035-disable-file-system-redirector/
从文档中引用:
“在 Python 3.5 之前,这三个函数组成了子进程的高级 API。您现在可以在许多情况下使用 run(),但许多现有代码调用这些函数。”
SO:代替 subprocess.call 使用 subprocess.run for Python 3.5 及更高版本
我在调用 PHP 时遇到了同样的问题。 原因是 PHP 不在 PATH 中,因此找不到 PHP 命令。 但是 PowerShell 发现它确实存在于当前位置,如果我信任此命令,它建议将 'PHP' 替换为 '.\\PHP'。 然后它运行良好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.