如何在Python子进程中清空stdout?

2 投票
2 回答
4076 浏览
提问于 2025-04-17 01:03

这个代码片段会在Windows系统中对一个IP地址进行ping操作,并每两秒输出一行结果。不过,我发现运行这个程序后,ping.exe这个进程的内存使用量会慢慢增加。如果我同时对1000个IP地址进行ping操作,服务器很快就会卡住。我觉得这可能是因为标准输出的缓冲区造成的。请问我该如何清理标准输出或者限制它的大小呢?谢谢!

...
proc = subprocess.Popen(['c:\windows\system32\ping.exe','127.0.0.1', '-l', '10000', '-t'],stdout=subprocess.PIPE, creationflags=subprocess.CREATE_NEW_PROCESS_GROUP) 

while True: 
    time.sleep(2)
    os.kill(proc.pid, signal.CTRL_BREAK_EVENT) 
    line = proc.stdout.readline() 

2 个回答

0

试试这个 ping.py,比起折腾 ping.exe 要简单很多。

1

ping命令产生的输出行数远远超过你正在读取的行数,这是因为在读取之间有2秒的超时时间。我建议把os.kill这个调用放到另一个线程中,然后用主线程来读取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()

撰写回答