gpt4 book ai didi

python-我们可以将临时文件与子进程一起使用以在 python 应用程序中获得非缓冲实时输出吗

转载 作者:太空宇宙 更新时间:2023-11-03 14:10:40 26 4
gpt4 key购买 nike

我正在尝试从 python windows 应用程序运行一个 python 文件。为此,我使用了 subprocess。为了在应用程序控制台上获取实时流输出,我尝试了以下语句。

带管道

p = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, shell=True)

for line in iter(p.stdout.readline, ''):
print line

(或)

process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
out = process.stdout.read(1)
if out == '' and process.poll() != None:
break
if out != '':
sys.stdout.write(out)
sys.stdout.flush()

不仅上面的代码,尝试了很多方法。得到如下相同的结果:

1.Python windows 应用程序运行时间过长

2.然后app窗口长时间进入“无响应”状态

3.然后整个输出打印在控制台上

我知道缓冲区溢出发生在 python 应用程序中,这就是我没有获得实时输出的原因。

我发布了很多关于这个问题的问题仍然没有得到解决。

刚刚找到并为此尝试了临时文件。但我不确定这是否会提供实时流输出。

我要试试这个吗?

import tempfile
import subprocess

w = tempfile.NamedTemporaryFile()
p = subprocess.Popen(cmd, shell=True, stdout=w,
stderr=subprocess.STDOUT, bufsize=0)

with open(w.name, 'r') as r:
for line in r:
print line
w.close()

或任何其他在 Windows 应用程序上实现非阻塞、无缓冲实时输出的最佳解决方案。

如有任何帮助,我们将不胜感激。

注意:1.我要运行的python文件有更多的打印语句(即更多的内容)

2.Windows server 2012,python 2.7

最佳答案

我知道你很沮丧。看来您自己几乎已经找到了答案。

我正在构建来自 this SO post 的答案.但是这个答案没有使用 TemporaryFile 而且我还使用了 here 中的 tail follow 方法我发现它能以非常大的输出量向终端提供最快的输出。这消除了对 print 的无关调用。

旁注:如果您还有其他异步操作要做,那么您可以将导入下面的代码包装在一个函数中,然后使用 gevent 包并导入sleep 来自 geventPopen, STDOUT 来自 gevent.subprocess。这就是我正在做的事情,可能会帮助您避免遗留下来的减速(我提到它的唯一原因)。

import sys
from tempfile import TemporaryFile
from time import sleep
from subprocess import Popen, STDOUT

# the temp file will be automatically cleaned up using context manager
with TemporaryFile() as output:
sub = Popen(cmd, stdout=output, stderr=STDOUT, shell=True)
# sub.poll returns None until the subprocess ends,
# it will then return the exit code, hopefully 0 ;)
while sub.poll() is None:
where = output.tell()
lines = output.read()
if not lines:
# Adjust the sleep interval to your needs
sleep(0.1)
# make sure pointing to the last place we read
output.seek(where)
else:
sys.__stdout__.write(lines)
sys.__stdout__.flush()
# A last write needed after subprocess ends
sys.__stdout__.write(output.read())
sys.__stdout__.flush()

关于python-我们可以将临时文件与子进程一起使用以在 python 应用程序中获得非缓冲实时输出吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38374063/

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