gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:27:00 25 4
gpt4 key购买 nike

此代码段将在 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()

关于python - 如何清除 Python 子进程中的标准输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7268960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com