Python subprocess store stdout and stderr output in a variable

To store stdout and stderr output in a variable use following code:

import os, sys, subprocess
from subprocess import *

#To store both stdout and stderr
output1 = subprocess.check_output("cat fileNotExists.txt; exit 0", stderr=subprocess.STDOUT, shell=True)
print "output1: ", output1

#To store only stdout
output2 = subprocess.check_output("cat fileNotExists.txt", stderr=subprocess.STDOUT, shell=True)
print "output2: ", output2

Output:

output1: cat: fileNotExists.txt: No such file or directory

Traceback (most recent call last):
File “subprocesss.py”, line 10, in <module>
output2=subprocess.check_output(“cat fileNotExists.txt”, stderr=subprocess.STDOUT, shell=True)
File “/usr/lib/python2.7/subprocess.py”, line 544, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command ‘cat fileNotExists.txt’ returned non-zero exit status 1

With subprocess.check_output(“cat fileNotExists.txt; exit 0”, stderr=subprocess.STDOUT, shell=True) we can store both stdout and stderr in a variable.

With subprocess.check_output(“cat fileNotExists.txt”, stderr=subprocess.STDOUT, shell=True) we can only store stdout, so we got error details as output.

I am tested this code with Python 2.7.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s