Monday, July 13, 2015

Execute a command, display output and get it's return code in Python

Often in my tests, I need to display the output and use the return code of the command I want to run. But I can't use check_output because my tests need to support RHEL6 and RHEL7 and RHEL6 is still on python 2.6.x and check_output is only available in Python 2.7

The following code snippet is modified from another website:

from subprocess import Popen, PIPE
 
cmd = "blah blah"
process = Popen(cmd.split(), stdout=PIPE)
process.communicate()    # execute it, the output goes to the stdout
exit_code = process.wait() # when finished, get the exit code


No comments:

Post a Comment