如何在python中执行ping或traceroute,以访问产生的输出? [英] How can I perform a ping or traceroute in python, accessing the output as it is produced?

查看:291
本文介绍了如何在python中执行ping或traceroute,以访问产生的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之前,我问了这个问题:

Earlier, I asked this question:

如何执行ping或使用本机python进行traceroute?

但是,由于python不是以root身份运行,因此它无法打开在本地python中执行ping/traceroute所需的原始ICMP套接字.

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.

这使我重新使用系统的ping/traceroute shell命令.这个问题有几个使用subprocess模块的示例,它们似乎运行良好:

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:

用Python ping网站?

不过,我还有一个要求:我需要能够访问产生的输出(例如,用于长时间运行的traceroute).

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.)

以上所有示例都运行shell命令,然后仅在命令完成后才使您可以访问完整的输出.有没有办法在产生命令输出时对其进行访问?

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?

编辑:根据Alex Martelli的回答,这是可行的方法:

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 是我的意思默认情况下"可以满足您的任何需求-还有其他类似的模块,但是pexpect几乎总是最丰富,最稳定和最成熟的模块.我要寻找替代方法的一种情况是,如果我也必须在Windows下正确运行(无论如何ping和traceroute可能都有其自身的问题),请告诉我们是否适合您,我们将看看可以安排什么!-)

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!-)

这篇关于如何在python中执行ping或traceroute,以访问产生的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆