Earlier, I asked this question:
However because python is not running as root it doens't have the ability to open the raw ICMP sockets needed to perform the ping/traceroute in native python.
This brings me back to using the system's ping/traceroute shell commands. This question has a couple examples using the subprocess module which seem to work well:
I still have one more requirement though: I need to be able to access the output as it is produced (eg. for a long running traceroute.)
The examples above all run the shell command and then only give you access to the complete output once the command has completed. Is there a way to access the command output as it is produced?
Edit: Based on Alex Martelli's answer, here's what worked:
import pexpect
child = pexpect.spawn('ping -c 5 www.google.com')
while 1:
line = child.readline()
if not line: break
print line,
解决方案
pexpect is what I'd reach for, "by default", for any requirement such as yours -- there are other similar modules, but pexpect is almost invariably the richest, most stable, and most mature one. The one case where I'd bother looking for alternatives would be if I had to run correctly under Windows too (where ping and traceroute may have their own problems anyway) -- let us know if that's the case for you, and we'll see what can be arranged!-)