Kartik Shenoy Kartik Shenoy - 1 year ago 136
Python Question

Running shell command from Python script

I'm trying to run a shell command from within a python script which needs to do several things

1. The shell command is 'hspice tran.deck >! tran.lis'

2. The script should wait for the shell command to complete before proceeding

3. I need to check the return code from the command and

4. Capture STDOUT if it completed successfully else capture STDERR

I went through the subprocess module and tried out a couple of things but couldn't find a way to do all of the above.

- with subprocess.call() I could check the return code but not capture the output.

- with subprocess.check_output() I could capture the output but not the code.

- with subprocess.Popen() and Popen.communicate(), I could capture STDOUT and STDERR but not the return code.

I'm not sure how to use Popen.wait() or the returncode attribute. I also couldn't get Popen to accept '>!' or '|' as arguments.

Can someone please point me in the right direction? I'm using Python 2.7.1

EDIT: Got things working with the following code

process = subprocess.Popen('ls | tee out.txt', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate()
print out
print err

Also, should I use a process.wait() after the process = line or does it wait by default?

Answer Source

Just use .returncode after .communicate(). Also, tell Popen that what you're trying to run is a shell command, rather than a raw command line:

p = subprocess.Popen('ls | tee out.txt', shell=True, ...)
print p.returncode
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download