Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a subprocess in Python?

I would like to create a subprocess of a process.

What would be a working example which shows how to accomplish this?

like image 943
sasa Avatar asked Dec 20 '10 09:12

sasa


4 Answers

Start with the subprocess documentation.

If you want to get the output:

>>> import subprocess
>>> output = subprocess.Popen(['uname', '-a'], stdout=subprocess.PIPE).communicate()[0]
>>> output
'Linux'

If you just want to call and not deal with the output:

>>> subprocess.call(['echo', 'Hi'])
Hi
0

subprocess.check_call is the same except that it throws up a CalledProcessError in case the command is called with invalid parameters.

A good subprocess tutorial.

like image 153
user225312 Avatar answered Oct 10 '22 20:10

user225312


Launching and monitoring a subprocess:

import subprocess, time, os, signal
args=['/usr/bin/vmstat','-n','2']
app=subprocess.Popen(args=args, stdout=open('somefile','w'))
print "Your app's PID is %s. You can now process data..." % app.pid
time.sleep(5)
if app.poll() == None: print "Process is still running after 5s."
print "The app outputed %s bytes." % len(open('somefile','r').read())
print "Stopping the process..."
os.kill(app.pid, signal.SIGTERM)

There is more to it. Just check the Popen docs.

like image 26
AXE Labs Avatar answered Oct 10 '22 21:10

AXE Labs


import subprocess

subprocess.call(['echo', 'hello world'])
like image 25
dan_waterworth Avatar answered Oct 10 '22 20:10

dan_waterworth


This is what worked for me if you want to run a simple command instead of giving a seperate file

import subprocess
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
process.wait()
print process.returncode

To get returncode of process you can use process.returncode To get response you can use process.communicate()

in case if you are confuse you can just test this code by using command="ls"

if you are getting returncode other than 0 then you can check here what that error code means: http://tldp.org/LDP/abs/html/exitcodes.html

For more details about Subprocess: http://docs.python.org/library/subprocess.html

like image 34
Zohab Ali Avatar answered Oct 10 '22 20:10

Zohab Ali