Starting a child process and getting its stdout?

Tom Plunket tomas at fancy.org
Fri Dec 29 03:59:41 EST 2006


cypher543 wrote:

> This has been driving me insane for the last hour or so. I have search
> everywhere, and nothing works. I am trying to use the subprocess module
> to run a program and get its output line by line. But, it always waits
> for the process to terminate and then return the output all at once.

Right, you need to use subprocess.PIPE and polling of the process and
the pipe to get it to do what you want.  Hopefully this makes sense, I
also hope it'll work on Linux but can't imagine why it wouldn't.

Save this code to a file, name unimportant.  Executing the file will
fire the top clause of the if statement, the bit that runs the "parent"
part.  That starts the script again as a subprocess, which triggers the
else clause.  Hope it makes sense.

Depending on your environment, you might need 'shell=True' in your Popen
args.  On Windows, that is required if you want to prevent a console
window from popping up if you're running in a GUI app.

-tom!

--

import subprocess
import sys
import time

if len(sys.argv) == 1:
	# no command line arg means, "we're the parent process."
	print 'starting parent process.'
	myName = sys.argv[0]
	
	# launch the subprocess with an additional parameter, to trigger
	# else clause below.
	p = subprocess.Popen(
		( 'python', '-u', myName, 'x' ),
		stdout=subprocess.PIPE
		)

	while p.poll() == None:
		data = p.stdout.readline()
		if data:
			print data,
			
	print 'process ended with return code', p.returncode
	
else:
	# assume the command-line arg means "run the background process"
	print 'starting subprocess'
	
	for i in range(10):
		time.sleep(.25)
		print i
		
	sys.exit(14)



More information about the Python-list mailing list