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

后端 未结 29 2671
醉酒成梦
醉酒成梦 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:02

    Try the asyncproc module. For example:

    import os
    from asyncproc import Process
    myProc = Process("myprogram.app")
    
    while True:
        # check to see if process has ended
        poll = myProc.wait(os.WNOHANG)
        if poll != None:
            break
        # print any new output
        out = myProc.read()
        if out != "":
            print out
    

    The module takes care of all the threading as suggested by S.Lott.

提交回复
热议问题