Flask: Showing print on website instead of console?


is there a simple way to put every print command from a script on the webpage instead of the console of the server? I found out that you could use the command yield, but this only seems to work for loops, not for print commands.

I tried this, but it couldn't work it out properly :/ How to continuously display Python output in a Webpage?

TypeError: can't concat bytes to str

My additional code is:

# ...
proc = subprocess.Popen(['script'],

when I write [script] instead of ['script'] I get a blank page which will load forever.

5/23/2017 12:22:21 PM

Accepted Answer

The error TypeError: can't concat bytes to str implies that you use Python 3 where python is more strict about mixing bytes and Unicode strings. You should also avoid mixing bytes and Unicode in Python 2 but python itself is more relax about it.

#!/usr/bin/env python3
import html
import sys
from subprocess import Popen, PIPE, STDOUT, DEVNULL
from textwrap import dedent

from flask import Flask, Response # $ pip install flask

app = Flask(__name__)

def index():
    def g():
        yield "<!doctype html><title>Stream subprocess output</title>"

        with Popen([sys.executable or 'python', '-u', '-c', dedent("""\
            # dummy subprocess
            import time
            for i in range(1, 51):
                time.sleep(.1) # an artificial delay
            """)], stdin=DEVNULL, stdout=PIPE, stderr=STDOUT,
                   bufsize=1, universal_newlines=True) as p:
            for line in p.stdout:
                yield "<code>{}</code>".format(html.escape(line.rstrip("\n")))
                yield "<br>\n"
    return Response(g(), mimetype='text/html')

if __name__ == "__main__":
    import webbrowser
    webbrowser.open('http://localhost:23423') # show the page in browser
    app.run(host='localhost', port=23423, debug=True) # run the server

See also Streaming data with Python and Flask.

5/23/2017 10:26:44 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow