任务是:尝试使用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 将在大约 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
<您现在使用的/a> 发送 SIGTERM
而不是 SIGINT
.
这篇关于ping 无限时间并在 Python 中获取其输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!