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

2024-10-01 15:48:43 发布

您现在位置:Python中文网/ 问答频道 /正文

这个代码段将ping windows中的一个ip地址,每2秒得到一个输出行,但是,我发现内存的增长非常缓慢ping.exe文件进程运行后,如果我把它部署到ping1000ip并行,很快就会造成服务器挂起,我想可能是因为stdout缓冲区的缘故,我可以知道如何清除stdout或者限制它的大小吗?谢谢!在

...
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() 

Tags: 文件内存ip服务器进程windows地址部署
2条回答

尝试ping.py而不是与ping.exe杂耍

由于两次读取之间的超时时间为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()

相关问题 更多 >

    热门问题