ping无限的时间并在Python中获取其输出 - python

任务是:尝试使用最基本的形式(例如“ ping 8.8.8.8”)在python中发送ping。一段时间后,终止ping命令(在终端中,将执行Ctrl + C)并获取其输出。显示ping统计信息的最后几行输出特别受关注。

尝试了两种方法,没有用。我的操作系统版本是Mac OS X 10.10.1。

第一种方法使用模块pexpect,虽然我没有要求它停止,但ping将在约17秒后停止:

import pexpect
import time
child = pexpect.spawn('ping 8.8.8.8')
(x, y) = child.getwinsize()
print x
print y
time.sleep(21)
child.terminate()
x = child.read()
print x

第二种方法使用模块子进程,并且ping输出的最后几行丢失:

import time
from subprocess import PIPE, Popen
child = Popen(['ping', '8.8.8.8'], stdin = PIPE, stdout = PIPE, stderr = PIPE)
time.sleep(5)
child.terminate()
x = child.stdout.read()
print x
x = child.stderr.read()
print x

我将不胜感激!不接受“ ping -c XXX”。

python大神给出的解决方案

您拥有的第二个解决方案很棒。获得所需的行为(获得ping的“结论”)只有一个问题:您向流程发送了错误的信号。

从外壳终止进程时,通常会发送SIGINT信号。请参见"bash - How does Ctrl-C terminate a child process?"。这允许进程“包装”(例如,清理临时文件,提供调试信息)。

import signal

# Open process

child.send_signal(signal.SIGINT)

# Provide some time for the process to complete
time.sleep(1)

# Echo output

您现在正在使用的Popen.terminate发送SIGTERM而不是SIGINT