python stdout清空_如何清除Python子进程中的stdout?

由于两次读取之间的超时时间为2秒,ping生成的行数比读取的多。我会把os.杀死调用另一个线程,并使用主线程读取proc.stdout中的每一行:import sys, os

import subprocess

import threading

import signal

import time

#Use ctrl-c and ctrl-break to terminate the script/ping

def sigbreak(signum, frame):

import sys

if proc.poll() is None:

print('Killing ping...')

proc.kill()

sys.exit(0)

signal.signal(signal.SIGBREAK, sigbreak)

signal.signal(signal.SIGINT, sigbreak)

#executes in a separate thread

def run(pid):

while True:

time.sleep(2)

try:

os.kill(pid, signal.CTRL_BREAK_EVENT)

except WindowsError:

#quit the thread if ping is dead

break

cmd = [r'c:\windows\system32\ping.exe', '127.0.0.1', '-l', '10000', '-t']

flags = subprocess.CREATE_NEW_PROCESS_GROUP

proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, creationflags=flags)

threading.Thread(target=run, args=(proc.pid,)).start()

while True:

line = proc.stdout.readline()

if b'statistics' in line:

#I don't know what you're doing with the ping stats.

#I'll just print them.

for n in range(4):

encoding = getattr(sys.stdout, 'encoding', 'ascii')

print(line.decode(encoding).rstrip())

line = proc.stdout.readline()

print()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值