Getting realtime output using subprocess

前端 未结 18 2791
执笔经年
执笔经年 2020-11-22 10:12

I am trying to write a wrapper script for a command line program (svnadmin verify) that will display a nice progress indicator for the operation. This requires me to be abl

18条回答
  •  耶瑟儿~
    2020-11-22 11:11

    Complete solution:

    import contextlib
    import subprocess
    
    # Unix, Windows and old Macintosh end-of-line
    newlines = ['\n', '\r\n', '\r']
    def unbuffered(proc, stream='stdout'):
        stream = getattr(proc, stream)
        with contextlib.closing(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)
                yield out
    
    def example():
        cmd = ['ls', '-l', '/']
        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
    
    example()
    

提交回复
热议问题