I'm using Python 3.4, and I'm trying to run the most simple command: subprocess.call(["dir"])
.
If I run subprocess.call(["dir"])
I get the following - FileNotFoundError: [WinError 2] The system cannot find the file specified
.
How can I fix this? I tried installing subprocess
with pip
, but it seems to be impossible.
You might want to not use shell=True as it is a security risk.
Also, you might want to get the result of subprocess.call, error messages and exit code to handle errors.
At last, always use a timeout on commands so your program won't get stuck (or thread them).
Here's a quick and dirty version you can use
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))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.