1

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:

script=r'C:\scripts\module.py'
# ...
proc = subprocess.Popen(['script'],

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

1 Answer 1

1

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

@app.route('/')
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):
                print(i)
                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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.