Getting realtime output using subprocess

前端 未结 18 2625
执笔经年
执笔经年 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 10:55

    In Python 3.x the process might hang because the output is a byte array instead of a string. Make sure you decode it into a string.

    Starting from Python 3.6 you can do it using the parameter encoding in Popen Constructor. The complete example:

    process = subprocess.Popen(
        'my_command',
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        shell=True,
        encoding='utf-8',
        errors='replace'
    )
    
    while True:
        realtime_output = process.stdout.readline()
    
        if realtime_output == '' and process.poll() is not None:
            break
    
        if realtime_output:
            print(realtime_output.strip(), flush=True)
    

    Note that this code redirects stderr to stdout and handles output errors.

提交回复
热议问题