[Tutor] Please correct my error handling

Mats Wichmann mats at wichmann.us
Thu Jan 2 13:44:56 EST 2020


On 1/2/20 11:12 AM, Robert Alexander wrote:
> 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.

also... there are "simpler" ways to do this vs Popen + communicate. I 
ran a "command fails" sequence in the interpreter:


 >>> x = subprocess.run(['/bin/ls', '-E'], stdout=subprocess.PIPE, 
stderr=subprocess.PIPE)
 >>> type(x)
 >>> <class 'subprocess.CompletedProcess'>
 >>> help(subprocess.CompletedProcess)
Help on class CompletedProcess in module subprocess:

class CompletedProcess(builtins.object)
  |  CompletedProcess(args, returncode, stdout=None, stderr=None)
  |
  |  A process that has finished running.
  |
  |  This is returned by run().
  |
  |  Attributes:
  |    args: The list or str args passed to run().
  |    returncode: The exit code of the process, negative for signals.
  |    stdout: The standard output (None if not captured).
  |    stderr: The standard error (None if not captured).
  |
  |  Methods defined here:
  |
  |  __init__(self, args, returncode, stdout=None, stderr=None)
  |      Initialize self.  See help(type(self)) for accurate signature.
  |
  |  __repr__(self)
  |      Return repr(self).
  |
  |  check_returncode(self)
  |      Raise CalledProcessError if the exit code is non-zero.
  |
  |  ----------------------------------------------------------------------
  |  Data descriptors defined here:
  |
  |  __dict__
  |      dictionary for instance variables (if defined)
  |
  |  __weakref__
  |      list of weak references to the object (if defined)

 >>> x.args
['/bin/ls', '-E']
 >>> x.returncode
2
 >>> x.stdout
b''
 >>> x.stderr
b"/bin/ls: invalid option -- 'E'\nTry '/bin/ls --help' for more 
information.\n"
 >>>


More information about the Tutor mailing list