python-2.7 - 如何在网页中连续显示 Python 输出?

标签 python-2.7 flask

我希望能够访问一个网页,它会运行一个 python 函数并在网页中显示进度。

因此,当您访问网页时,您可以看到脚本的输出,就像从命令行运行它一样。

基于这里的答案

How to continuously display python output in a webpage?

我正在尝试显示来自 的输出 python

我正在尝试将 Markus Unterwaditzer 的代码与 python 函数一起使用。

import flask
import subprocess

app = flask.Flask(__name__)

def test():
    print "Test"

@app.route('/yield')
def index():
    def inner():
        proc = subprocess.Popen(
            test(),
            shell=True,
            stdout=subprocess.PIPE
        )

        while proc.poll() is None:
            yield proc.stdout.readline() + '<br/>\n'
    return flask.Response(inner(), mimetype='text/html')  # text/html is required for most browsers to show the partial page immediately

app.run(debug=True, port=5005)

它运行但我在浏览器中看不到任何内容。

最佳答案

嗨,您似乎不想调用测试函数,而是调用提供输出的实际命令行进程。还可以从 proc.stdout.readline 或其他东西创建一个迭代。你还从 Python 中说到,我忘了包括你应该在子进程中提取任何你想要的 Python 代码并将它放在一个单独的文件中。

import flask
import subprocess
import time          #You don't need this. Just included it so you can see the output stream.

app = flask.Flask(__name__)

@app.route('/yield')
def index():
    def inner():
        proc = subprocess.Popen(
            ['dmesg'],             #call something with a lot of output so we can see it
            shell=True,
            stdout=subprocess.PIPE
        )

        for line in iter(proc.stdout.readline,''):
            time.sleep(1)                           # Don't need this just shows the text streaming
            yield line.rstrip() + '<br/>\n'

    return flask.Response(inner(), mimetype='text/html')  # text/html is required for most browsers to show th$

app.run(debug=True, port=5000, host='0.0.0.0')

关于python-2.7 - 如何在网页中连续显示 Python 输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15092961/

相关文章:

python - 总结 Python 2 中计数器的所有值

python - 修改列表中的元组

python - 无法在终端上打开 Python 脚本

javascript - Flask 处理前端 AJAX 调用错误的正确方法

python - flask-sqlalchemy 表编辑未显示

python - 从html文件中导入表的行作为python中的列表

python - 如何加载网页(不在浏览器中)然后获取该网页的网址?

python-2.7 - 使用网页回放录制 HTTPS 网页

python - 在 flask/gunicorn 中初始化应用程序的位置

python - 使用 CGI 部署 Flask 应用程序