Python Forum
Flask read real time print from subprocess without deadlock - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Web Scraping & Web Development (https://python-forum.io/forum-13.html)
+--- Thread: Flask read real time print from subprocess without deadlock (/thread-33853.html)



Flask read real time print from subprocess without deadlock - vofka32 - Jun-02-2021

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')