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

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

    I have often had a similar problem; Python programs I write frequently need to have the ability to execute some primary functionality while simultaneously accepting user input from the command line (stdin). Simply putting the user input handling functionality in another thread doesn't solve the problem because readline() blocks and has no timeout. If the primary functionality is complete and there is no longer any need to wait for further user input I typically want my program to exit, but it can't because readline() is still blocking in the other thread waiting for a line. A solution I have found to this problem is to make stdin a non-blocking file using the fcntl module:

    import fcntl
    import os
    import sys
    
    # make stdin a non-blocking file
    fd = sys.stdin.fileno()
    fl = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
    
    # user input handling thread
    while mainThreadIsRunning:
          try: input = sys.stdin.readline()
          except: continue
          handleInput(input)
    

    In my opinion this is a bit cleaner than using the select or signal modules to solve this problem but then again it only works on UNIX...

提交回复
热议问题