我正在尝试从python Windows应用程序运行一个python文件。为此,我使用了subprocess。为了在应用程序控制台上获得实时流输出,我尝试了以下语句。
带PIPE
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.然后,应用程序窗口长时间处于“无响应”状态
3.然后将整个输出打印在控制台上
我知道python应用程序中正在发生缓冲区溢出,这就是为什么我没有实时输出的原因。
我为此发布了很多查询,但仍然没有解决方案。
刚刚找到并尝试了这个的tempfile。但是我不确定这将提供实时流输出。
我可以这样尝试吗?
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
小智 5
我了解您很沮丧。看来您差不多自己回答了。
我正在以此SO帖子的答案为基础。但是这个答案没有用TemporaryFile,而且我从这里开始使用了尾部跟踪方法,我发现该方法可以为终端提供最快的输出,输出量非常大。这消除了对的多余调用print。
附注:如果你有其他异步的东西做,那么你可以包进口下面的代码在功能和使用的gevent包装和进口sleep的gevent和Popen, 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()
| 归档时间: | 
 | 
| 查看次数: | 2822 次 | 
| 最近记录: |