[Tutor] Please correct my error handling
Robert Alexander
gogonegro at gmail.com
Fri Jan 3 09:54:15 EST 2020
Thank you guys.
So as you pointed out I was catching the error at the wrong place.
Following is the corrected code. I’ll also investigate the easier
alternatives you proposed later on.
Take care
import subprocess
# first try a legit (*nix) command
process = subprocess.Popen(
["/bin/ls", "-l"], stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
stdout, stderr = process.communicate()
if not stderr:
print("--No errors--\n", stdout.decode())
else:
print("--Error found--\n", stderr.decode())
# now repeat with an illegal option
process = subprocess.Popen(
["/bin/ls", "-I"], stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
stdout, stderr = process.communicate()
if not stderr:
print("--No errors--\n", stdout.decode())
else:
print("--Error found--\n", stderr.decode())
# now repeat with an inexisting command
# and catch the Popen error this time
try:
process = subprocess.Popen(
["/bin/lsd", "-I"], stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
except FileNotFoundError:
print("Command not found. Did you install it?")
else:
stdout, stderr = process.communicate()
if not stderr:
print("--No errors--\n", stdout.decode())
else:
print("--Error found--\n", stderr.decode())
More information about the Tutor
mailing list