这个片段会在Windows中ping一个ip地址并且每2秒获得一次输出行,但是,我发现运行它后ping.exe进程的内存增长很慢,如果我将它部署到ping 1000 ip parallel,很快它会导致服务器挂起,我认为可能是因为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 :(得分:1)
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()
答案 1 :(得分:0)
尝试使用ping.py,而不是使用ping.exe