[Tutor] Please correct my error handling

David Rock david at graniteweb.com
Thu Jan 2 13:39:18 EST 2020


* Robert Alexander <gogonegro at gmail.com> [2020-01-02 19:12]:
> I am having an hard time to properly address some errors in external
> programs launched by my python code.

> # 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())


The problem is process.communicate() is thowing an exception.  That's
not the same thing as getting stdout, stderr

Traceback (most recent call last):
  File "test.py", line 6, in <module>
    stderr=subprocess.PIPE,
  File "/usr/lib/python3.5/subprocess.py", line 676, in __init__
    restore_signals, start_new_session)
  File "/usr/lib/python3.5/subprocess.py", line 1282, in _execute_child
    raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: '/bin/lsd'


The FileNotFoundError is an exception from process.communicate() failing
outright.  You need to catch that exception and do something with it.
For example, put the call to process.communicate() in a try block.

try:
    stdout, stderr = process.communicate()
except FileNotFoundError:
    print( "command not found" )
else:
    if not stderr:
        print('--No errors--\n', stdout.decode())
    else:
        print('--Error found--\n', stderr.decode())

-- 
David Rock
david at graniteweb.com


More information about the Tutor mailing list