python执行ping并输出_如何在python中执行ping或traceroute,并访问产生的输出?

这篇博客介绍了如何使用Python的pexpect模块来实时获取系统命令(如ping和traceroute)的输出,特别是在需要连续获取输出信息的场景下。通过pexpect,可以实现与子进程的交互,从而在命令运行过程中获取并处理输出。
摘要由CSDN通过智能技术生成

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值