Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running shell command from Python script

Tags:

python

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()
if(process.returncode==0):
  print out
else:
  print err

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

like image 212
kshenoy Avatar asked Dec 17 '22 02:12

kshenoy


1 Answers

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, ...)
p.communicate()
print p.returncode
like image 123
Niklas B. Avatar answered Dec 18 '22 15:12

Niklas B.