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

后端 未结 29 2595
醉酒成梦
醉酒成梦 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条回答
  •  -上瘾入骨i
    2020-11-21 05:16

    I add this problem to read some subprocess.Popen stdout. Here is my non blocking read solution:

    import fcntl
    
    def non_block_read(output):
        fd = output.fileno()
        fl = fcntl.fcntl(fd, fcntl.F_GETFL)
        fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
        try:
            return output.read()
        except:
            return ""
    
    # Use example
    from subprocess import *
    sb = Popen("echo test && sleep 1000", shell=True, stdout=PIPE)
    sb.kill()
    
    # sb.stdout.read() # <-- This will block
    non_block_read(sb.stdout)
    'test\n'
    

提交回复
热议问题