簡體   English   中英

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

[英]How to clear stdout in Python subprocess?

該代碼段將在Windows中ping一個IP地址並每2秒獲取一條輸出線,但是,我發現運行它后ping.exe進程的內存增加非常緩慢,如果我將它部署到ping 1000 ip並行,很快它將導致服務器掛起,我認為可能是因為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() 

由於讀取之間的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()

嘗試ping.py而不是與ping.exe玩弄

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM