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

标签 python python-2.7 flask jinja2

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

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

我需要在函数中做什么?

我需要在模板中做什么?

编辑:

我正在尝试将 Markus Unterwaditzer 的代码与模板结合使用。

{% extends "base.html" %}
{% block content %}

{% autoescape false %}

{{word}}

{% endautoescape %}

{% endblock %}

Python代码

import flask
from flask import render_template
import subprocess
import time

app = flask.Flask(__name__)

@app.route('/yield')
def index():
    def inner():
        for x in range(1000):
            yield '%s<br/>\n' % x
            time.sleep(1)
    return render_template('simple.html', word=inner())
    #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=8080)

它运行了,但我在浏览器中看不到任何东西。

最佳答案

这是一个非常简单的应用程序,它使用普通 HTTP 流式传输进程的输出:

import flask
import time

app = flask.Flask(__name__)

@app.route('/yield')
def index():
    def inner():
        for x in range(100):
            time.sleep(1)
            yield '%s<br/>\n' % x
    return flask.Response(inner(), mimetype='text/html')  # text/html is required for most browsers to show the partial page immediately

app.run(debug=True)

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

相关文章:

python 2.7 : get the size of a file just from its handle (and not its path)

python - 在 Jupyter 笔记本中显示 Flask 应用程序输出

postgresql - Flask sqlAlchemy 手册 ORM : 'RelationshipProperty' object has no attribute 'parent'

python - argparse 不转换默认数字参数?

python - 我可以使用 mod_python 在 Apache 服务器上运行 Flask 吗?

python - 从6月1日到5月31日,如何每年重新采样?

python CGI : upload error

Python:为什么 * 和 ** 比/和 sqrt() 快?

python - c++中的嵌入式python代码-导入python库时出错

python - 任何使用 rrule 向后移动的方法