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

2024-05-14 21:40:27 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种简单的方法可以将来自脚本的每个打印命令放在网页上而不是服务器的控制台上?我发现您可以使用命令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']时,我会得到一个永远加载的空白页。


Tags: to方法in命令服务器脚本网页output
1条回答
网友
1楼 · 发布于 2024-05-14 21:40:27

错误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

相关问题 更多 >

    热门问题