After I read this twice, I realized it's ten years old and most answers apply to the now deprecated python2.7 rather than python3.
Now that we are - or should be - on python3, it seems that the best option for python >= 3.7 is to use the following as is mentioned in multiple comments:
result = subprocess.run(..., check=True, capture_output=True)
To save you searching for more details, I recommend an answer I found with wonderful detail by SethMMorton in an answer to "How to suppress or capture the output of subprocess.run()?" As described there, you can access stdout, stderr directly as:
print(result.stdout)
print(result.stderr)
If you need to support Python 3.6:
You can however easily "emulate" this by setting both stdout
and stderr
to PIPE
:
from subprocess import PIPE
subprocess.run(["ls", "-l", "/dev/null"], stdout=PIPE, stderr=PIPE)
This info is from
Willem Van Onsem's answer to a related question.
I tend to go straight to https://docs.python.org/3/library/subprocess.html to refresh my memory on general subprocess things. (The SO examples are often easier for me to access quickly though.)