Python 3.4子进程FileNotFoundError WinError 2

时间:2020-02-11 22:03:06

标签: python python-3.x subprocess

我正在使用Python 3.4,并且试图运行最简单的命令:subprocess.call(["dir"])

如果我运行subprocess.call(["dir"]),我将得到以下内容-FileNotFoundError: [WinError 2] The system cannot find the file specified

我该如何解决?我尝试将subprocesspip一起安装,但这似乎是不可能的。

1 个答案:

答案 0 :(得分:1)

您可能不希望使用shell = True,因为它存在安全风险。

此外,您可能希望获取subprocess.call的结果,错误消息和退出代码以处理错误。

最后,请始终对命令使用超时,这样您的程序就不会卡住(或线程化)。

这是您可以使用的快速而肮脏的版本

import os
import subprocess

# Your command
command = 'dir'

# Forge your command using an absolute path
shell_command = '"%s" /c %s' % (os.path.join(os.environ['SYSTEMROOT'], 'system32', 'cmd.exe'), command)
try:
    # Execute the command with a timeout, and redirct error messages to your output
    output = subprocess.check_output(shell_command, timeout=10, stderr=subprocess.STDOUT, shell=False, universal_newlines=True)
    exit_code = 0
# Handle possible errors and get exit_code
except subprocess.CalledProcessError as exc:
    output = ""
    exit_code = exc.returncode

# Show results
print('[%s] finished with exit code %s\nResult was\n\n%s' % (command, exit_code, output))
相关问题