Skip to main content
 首页 » 编程设计

python之如何清除 Python 子进程中的标准输出

2025年05月04日14yxwkf

此代码段将在 Windows 中 ping 一个 ip 地址并每 2 秒获取一次输出行,但是,我发现运行后 ping.exe 进程的内存增加非常缓慢,如果我将它部署到 ping 1000 ip parallel,很快它会导致服务器挂起,我想这可能是因为标准输出缓冲区,我可以知道如何清除标准输出或限制其大小吗?谢谢!

... 
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 秒的超时,ping 生成的行数比您正在读取的行数多得多。我会将 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()