Using subprocess.Popen for Process with Large Output

后端 未结 7 1934
礼貌的吻别
礼貌的吻别 2020-12-02 16:56

I have some Python code that executes an external app which works fine when the app has a small amount of output, but hangs when there is a lot. My code looks like:

相关标签:
7条回答
  • 2020-12-02 17:57

    Reading stdout and stderr independently with very large output (ie, lots of megabytes) using select:

    import subprocess, select
    
    proc = subprocess.Popen(cmd, bufsize=8192, shell=False, \
        stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    
    with open(outpath, "wb") as outf:
        dataend = False
        while (proc.returncode is None) or (not dataend):
            proc.poll()
            dataend = False
    
            ready = select.select([proc.stdout, proc.stderr], [], [], 1.0)
    
            if proc.stderr in ready[0]:
                data = proc.stderr.read(1024)
                if len(data) > 0:
                    handle_stderr_data(data)
    
            if proc.stdout in ready[0]:
                data = proc.stdout.read(1024)
                if len(data) == 0: # Read of zero bytes means EOF
                    dataend = True
                else:
                    outf.write(data)
    
    0 讨论(0)
提交回复
热议问题