I've been playing with
Peter Astrand's Popen5 module lately.
It's
really nice and I hope that it will be accepted into Python's standard
library eventually via
PEP 324
.
I like this module because it allows nice and easy control over child
processes. I get full control of the child's stdin, stdout, and stderr without
having to do the dup dance (which I'd always have to lookup before this).
And I can make an easy timeout without having to use SIGALRM.
I especially appreciate Popen5 in light of having spent way too much time
tring to get a simple return value out of Twisted's utils.getProcessValue()
last weekend. But that was mostly my fault.
Here's an example of using Popen5:
import popen5
import time
import os
import signal
def main():
wait_time = 5 # seconds
args = ['/sbin/ping', '-i', '10', 'localhost']
outf = open('ping.out', 'w+')
errf = open('ping.err', 'w+')
ping = popen5.Popen(args, stdout=outf, stderr=errf)
print 'ping started with pid ', ping.pid
time_done = time.time() + wait_time
while ping.poll() == -1:
if time.time() > time_done:
print 'bored now!'
os.kill(ping.pid, signal.SIGINT)
time.sleep(1)
os.waitpid(ping.pid, os.WNOHANG)
break
else:
time.sleep(1)
for f in [outf, errf]:
f.seek(0)
output = f.read()
if output:
print 'Contents of %s:' % f.name
print output
if __name__ == '__main__':
main()
Take care.
P.S. Thanks to everyone who's left comments here. I'm learning a lot,
and feel more like a member of the global Python community now. Since I
won't make it to either PyCon or OSCON this year, I'm glad I have this.
|