ping无限的时间,并在Python中获取其输出 [英] ping for indefinite amount of time and get its output in Python
问题描述
任务是:尝试使用最基本的形式(如"ping 8.8.8.8")在python中发送ping.一段时间后,终止ping命令(在终端中,将执行Ctrl + C)并获取其输出.显示ping统计信息的最后几行输出特别受关注.
The task is: Try to send ping in python using the most basic form like "ping 8.8.8.8". After some time terminate the ping command (In a terminal, one will do Ctrl+C) and get its output. The last several lines of output which shows the ping statistics are of particular interest.
尝试了两种方法,没有用.我的操作系统版本是Mac OS X 10.10.1.
Two methods tried, did not work. My OS version is Mac OS X 10.10.1.
第一种方法使用模块pexpect,虽然我不要求ping停止,但ping会在约17秒后停止:
First method uses module pexpect, and ping will stop after about 17 seconds though I did not ask it to stop:
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输出的最后几行丢失:
Second Method uses module subprocess, and the last several lines of ping output are lost:
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".
I'd appreciate any help! "ping -c XXX" is not accepted.
推荐答案
您拥有的第二个解决方案很棒.获得所需的行为(获取ping
的结论")只有一个问题:您向流程发送了错误的信号.
The second solution you have is great. There's just one issue with obtaining your desired behavior (getting the ping
's "conclusion"): You're sending the wrong signal to the process.
从shell终止进程时,通常会发送SIGINT
信号.请参见"bash-Ctrl-C如何终止子进程?" .这样可以使过程结束"(例如,清理临时文件,提供调试信息).
When you terminate the process from a shell, you traditionally send a SIGINT
signal. See "bash - How does Ctrl-C terminate a child process?". This allows the process to "wrap up" (e.g., cleaning up temprorary files, providing debug information).
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
.
这篇关于ping无限的时间,并在Python中获取其输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!