Python Forum

Full Version: Flask read real time print from subprocess without deadlock
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello. Maybe someone could help? The problem is with subprocess.
I need to run the subprocess (generator.py) and show the output real-time on HMTL via Flask . As this subprocess starts, Flask switches to deadlock. And all the generated information is obtained only at the end of the subprocess. It's clear that everything works on localhost on Windows, but not on Linux. Maybe someone knows how to get around that deadlock? See example below.

generator.py
import random
from time import sleep
for i in range(0, 20, 1):
    sleep(0.5)
    print(random.randint(0, 100))
app.py
@app.route('/interactive')
def interactive():
    def read():
        proc = subprocess.Popen(
            ["python3", "users/ID4/generator.py"], stdout=subprocess.PIPE, stdin=subprocess.PIPE)
        for line in iter(proc.stdout.readline, ""):
            yield line
    return Response(read(), mimetype='text/html')


@app.route('/stream123')
def stream123():
    def generate():
        process = subprocess.Popen("ping -c 5 google.com", stdout=subprocess.PIPE, shell=True)
        while True:
            line = process.stdout.readline().rstrip()
            if not line:
                break
            yield line
    return Response(generate(), mimetype='text/html')