A non-blocking read on a subprocess.PIPE in Python

后端 未结 29 2652
醉酒成梦
醉酒成梦 2020-11-21 04:49

I\'m using the subprocess module to start a subprocess and connect to its output stream (standard output). I want to be able to execute non-blocking reads on its standard ou

29条回答
  •  时光说笑
    2020-11-21 05:16

    One solution is to make another process to perform your read of the process, or make a thread of the process with a timeout.

    Here's the threaded version of a timeout function:

    http://code.activestate.com/recipes/473878/

    However, do you need to read the stdout as it's coming in? Another solution may be to dump the output to a file and wait for the process to finish using p.wait().

    f = open('myprogram_output.txt','w')
    p = subprocess.Popen('myprogram.exe', stdout=f)
    p.wait()
    f.close()
    
    
    str = open('myprogram_output.txt','r').read()
    

提交回复
热议问题