Flask:如何在网站上显示打印而非控制台?

1 投票
1 回答
8886 浏览
提问于 2025-04-18 00:49

有没有简单的方法可以把脚本里的每个打印命令都显示在网页上,而不是服务器的控制台里?我发现可以用命令 yield,但这似乎只适用于循环,而不适用于打印命令。

我试过这样做,但没有成功 :/ 如何在网页上持续显示Python输出?

TypeError: can't concat bytes to str

我额外写的代码是:

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

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

1 个回答

1

这个错误 TypeError: can't concat bytes to str 表示你在使用 Python 3。在这个版本中,Python 对字节(bytes)和 Unicode 字符串的混合使用比较严格。虽然在 Python 2 中也应该避免混合使用字节和 Unicode,但那个版本对这方面的限制要宽松一些。

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

你可以查看这个链接了解更多内容:使用 Python 和 Flask 进行数据流处理

撰写回答