我正在使用Python 3.4,并且试图运行最简单的命令:subprocess.call(["dir"])
。
如果运行subprocess.call(["dir"])
,将得到以下内容-FileNotFoundError: [WinError 2] The system cannot find the file specified
。
我该如何解决?我尝试将subprocess
与pip
一起安装,但这似乎是不可能的。
您可能不希望使用shell = True,因为它存在安全风险。另外,您可能希望获取subprocess.call,错误消息和退出代码的结果以处理错误。最后,请始终对命令使用超时,以免您的程序卡住(或使它们线程化)。
这里是您可以使用的快速而肮脏的版本
import os
import subprocess
# Forge your command using an absolute path
command = '"%s" /c dir' % os.path.join(os.environ['SYSTEMROOT'], 'system32', 'cmd.exe')
try:
# Execute the command with a timeout, and redirct error messages to your output
output = subprocess.check_output(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))