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

后端 未结 29 2566
醉酒成梦
醉酒成梦 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 04:57

    On Unix-like systems and Python 3.5+ there's os.set_blocking which does exactly what it says.

    import os
    import time
    import subprocess
    
    cmd = 'python3', '-c', 'import time; [(print(i), time.sleep(1)) for i in range(5)]'
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    os.set_blocking(p.stdout.fileno(), False)
    start = time.time()
    while True:
        # first iteration always produces empty byte string in non-blocking mode
        for i in range(2):    
            line = p.stdout.readline()
            print(i, line)
            time.sleep(0.5)
        if time.time() > start + 5:
            break
    p.terminate()
    

    This outputs:

    1 b''
    2 b'0\n'
    1 b''
    2 b'1\n'
    1 b''
    2 b'2\n'
    1 b''
    2 b'3\n'
    1 b''
    2 b'4\n'
    

    With os.set_blocking commented it's:

    0 b'0\n'
    1 b'1\n'
    0 b'2\n'
    1 b'3\n'
    0 b'4\n'
    1 b''
    

提交回复
热议问题