Python Subprocess usage summary

Preamble
import subprocess
cmd = ['command', 'option1', 'option2', '...']
Run a command, block until it finishes, and get the return code
returncode = subprocess.call(cmd)
Run a command, block until it finishes, and get its output to stdout and stderr and the return code
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
returncode = proc.returncode
Run a command, do not block but read the output from the process, and get the return code when it finishes
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

import sys
output_text = ''
while True:
	output = proc.stdout.read(1)
	if output == '': break
	sys.stdout.write(output)
	output_text += output

returncode = proc.wait()
Run a command, and send the input to the process
input_text = 'some input to the process'
proc = subprocess.Popen(cmd, stdin=PIPE)
proc.communicate(input=input_text)
Advertisements
Python Subprocess usage summary

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