[Tutor] Please correct my error handling
Robert Alexander
gogonegro at gmail.com
Thu Jan 2 13:12:36 EST 2020
I am having an hard time to properly address some errors in external
programs launched by my python code.
Here follows a sample, in which you can see 3 similar “stanzas”, first is
to check behaviour of a well formed external command and is all as
expected, the second shows the same command with an illegal option and
again all behaves as expected. The problem I have is to catch the “non
existing command” as per the third example.
Thank you very much.
Robert
============== test.py
import subprocess
# 1) 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())
# 2) 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())
# 3) repeat with an illegal ;) command
process = subprocess.Popen(
['/bin/lsd', '-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())
More information about the Tutor
mailing list