2011-09-01 79 views
2

這段代碼會在windows中ping一個ip地址並每2秒得到一個輸出行,但是,我發現ping.exe進程在運行後會有非常緩慢的內存增加,如果我將它部署到ping 1000 ip並行,會導致服務器掛起,我認爲這可能是由於stdout緩衝區,我可以知道如何清除標準輸出或限制其大小?謝謝!如何清除Python子流程中的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() 
+0

你包含轉義反斜線串的作品,因爲'\ w','\ s'和'\ p'不是轉義序列,所以Python會將反斜槓視爲反斜槓。雖然這不是一個好主意。你應該避免反斜槓(加倍)或使用原始字符串('r'...'')。 –

回答

1

平比你正在閱讀由於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()