任务是:尝试使用最基本的形式(如“ 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”。
您拥有的第二个解决方案很棒。获得所需的行为(获得ping
“结论”)只有一个问题:您向流程发送了错误的信号。
从外壳终止进程时,通常会发送SIGINT
信号。请参阅“ bash-Ctrl-C如何终止子进程?” 。这允许进程“包装”(例如,清理临时文件,提供调试信息)。
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
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句