subprocess solved all my problems

Jacek Popławski jpopl at interia.pl
Fri Sep 9 07:22:04 EDT 2005


In the last week I was working to create script which will read command 
from socket, call it, return result, stdout, stderr and kill it after 
timeout.
After playing with threads, processes, spawns and popens I found 
subprocess module.

To call command I use following construction:

		finish=time.time()+self.timeout						 
self.p=subprocess.Popen(self.command,shell=True,
			stdout=subprocess.PIPE,stderr=subprocess.PIPE)
		while (self.p.poll()==None) and (time.time()<finish):
			pass #FIXME more CPU friendly
		result=self.p.poll();
		if (result==None):
			print "kill!"
			os.kill(self.p.pid,9)
		return result

then to get its stdout:

self.p.stdout.read()



More information about the Python-list mailing list