I often wish to perform the action of `subprocess.check_output`, i.e. print 
STDOUT live, and check the return code is 0 on exit. However  if there is an 
error, I would like the STDERR to be printed. When looking at log files and 
just seeing the return code is often not very beneficial.

E.g.:

```py
subprocess.check_call(['ping', '-c', '1', 'github.com2'])
```

Will generate this error:
```
subprocess.CalledProcessError: Command '['ping', '-c', '1', 'github.com2']' 
returned non-zero exit status 2.
```

Here we are left wondering why it failed, on real world examples it becomes 
critical to be able to see what the actual error is. So I find I always have to 
wrap such calls in something like this to be able to see STDERR:

```
import subprocess
cmds = ['ping', '-c', '1', 'github.com2']
result = subprocess.run(cmds, stderr=subprocess.PIPE)
if result.returncode != 0:
    msg = result.stderr.decode().strip()
    raise subprocess.CalledProcessError(f"CALLED SUBPROCESS ERROR: Command: {' 
'.join(cmds)}\nReturn code {result.returncode}\nSTDERR: {msg}\n")
```

With the above one gets to see that STDERR is:
```
ping: github.com2: Temporary failure in name resolution
```
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/7PVHSJGKFUIV4ZJFWG7EU3DR6XAGAKQW/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to