Flask:在网站上显示打印而不是控制台?

时间:2014-04-01 11:18:24

标签: python python-3.x flask subprocess popen

有一种简单的方法可以将来自脚本的每个打印命令放在网页而不是服务器的控制台上吗?我发现你可以使用命令yield,但这似乎只适用于循环,而不适用于打印命令。

我试过这个,但它无法正常使用:/ How to continuously display Python output in a Webpage?

TypeError: can't concat bytes to str

我的附加代码是:

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

当我写[script]而不是['script']时,我会得到一个永久加载的空白页。

1 个答案:

答案 0 :(得分:1)

错误TypeError: can't concat bytes to str意味着您使用Python 3,其中python对混合字节和Unicode字符串更严格。你还应该避免在Python 2中混合使用字节和Unicode,但是python本身对它更加放松。

#!/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

另见Streaming data with Python and Flask

相关问题