Search code examples
pythonsubprocesspopen

Way to prevent stdout.readline() from freezing program


In my current program, I start a server using subprocess.Popen() and continue reading from the stdout using readline(). However, when it gets stuck on readline until a new line appears. This is bad because I need to be able to execute other code while waiting for the server to output. Is there a way I can stop this from occurring?

import subprocess

server = subprocess.Popen("startup command", stdout= subprocess.PIPE, encoding= "utf-8")

while True:
    out = server.stdout.readline()
    if out != "":
        print(out)
    print("checked for line")

i would prefer to avoid having to multi-thread because different parts of my code would no longer be thread-safe.


Solution

  • You're going to want to use threading as @tim Roberts said. What you'll need to do is have your read loop post events to the main thread. Whether that is with global flags or a queue. Take a look at the documentation for queue.

    https://docs.python.org/3/library/queue.html