Popen在漫长的过程中重定向stdout

时间:2015-01-30 16:54:48

标签: python-3.x popen

我已经做了一些测试来在长时间的过程中重定向stdout。

我得到了一些我不明白的结果。

run.py

import contextlib
import subprocess
import sys

newlines = ['\n', '\r\n', '\r']


def example1():
    #stupid test, for fun
    cmd = ['python', 'in.py']
    proc = subprocess.Popen(
        cmd,
        stdout=sys.stdout,
        stderr=sys.stderr,
    )

def example2():

    # http://stackoverflow.com/questions/803265/getting-realtime-output-using-subprocess
    def unbuffered(proc, stream='stdout'):
        stream = getattr(proc, stream)
        while True:
            out = []
            last = stream.read(1)
            # Don't loop forever
            if last == '' and proc.poll() is not None:
                break
            while last not in newlines:
                # Don't loop forever
                if last == '' and proc.poll() is not None:
                    break
                out.append(last)
                last = stream.read(1)
            out = ''.join(out)
            print(out)

    cmd = ['python', 'in.py']
    proc = subprocess.Popen(
        cmd,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        # Make all end-of-lines '\n'
        universal_newlines=True,
    )
    for line in unbuffered(proc):
        print(line)

def example3():
    #http://stackoverflow.com/questions/4417546/constantly-print-subprocess-output-while-process-is-running
    cmd = ['python', 'in.py']
    popen = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    lines_iterator = iter(popen.stdout.readline, b"")
    while popen.poll() is None:
        for line in lines_iterator:
            nline = line.rstrip()
            print(nline.decode("latin"), end="\r\n",flush=True)

in.py

import random
import sys
import time

END = 10

for i in range(END):
    print(i)
    if i == random.randint(1, END-2):
        sys.stderr.write('Error, out !!!\n')
        sys.exit(i)
    time.sleep(0.2)

示例1

惊喜......我可以将stdout重定向到控制台(不适用于bpython)。奇怪的是我必须按一个键才能完成这个过程。

example2 example3

仅在子流程结束时输出打印。

我在子处理方面相当新,谢谢你的解释。 :)

0 个答案:

没有答案