简体   繁体   English

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

[英]How to continuously display python output in a webpage?

I want to be able to visit a webpage and it will run a python function and display the progress in the webpage. 我希望能够访问一个网页,它将运行一个python函数并在网页中显示进度。

So when you visit the webpage you can see the output of the script as if you ran it from the command line and see the output in the command line. 因此,当您访问该网页时,您可以看到脚本的输出,就像您从命令行运行它并在命令行中查看输出一样。

What do I need to do in the function? 我需要在函数中做什么?

What do I need to do in the template? 我需要在模板中做什么?

EDIT: 编辑:

I am trying to use Markus Unterwaditzer's code with a template. 我正在尝试使用Markus Unterwaditzer的代码和模板。

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

{% autoescape false %}

{{word}}

{% endautoescape %}

{% endblock %}

Python code 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)

And it runs but I don't see anything in the browser. 它运行但我在浏览器中看不到任何内容。

Here is a very simple app that streams a process' output with normal HTTP: 这是一个非常简单的应用程序,使用普通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)

I had the same problem today, and found a way to adapt Markus Unterwaditzer's answer to work with a template. 我今天也遇到了同样的问题,并找到了一种方法来改变Markus Unterwaditzer对模板工作的回答。

The key is to use jinja's Template.generate() instead of Template.render() , which is used by flask's render_template() . 关键是使用jinja的Template.generate()而不是Template.render() ,它由flask的render_template()

import flask
import time

from jinja2 import Environment
from jinja2.loaders import FileSystemLoader

app = flask.Flask(__name__)

@app.route('/yield')
def index():
    def inner():
        for x in range(100):
            time.sleep(1)
            yield '%s<br/>\n' % x
    env = Environment(loader=FileSystemLoader('templates'))
    tmpl = env.get_template('result.html')
    return flask.Response(tmpl.generate(result=inner()))

app.run(debug=True)

Assuming that there is a template result.html that looks like this: 假设有一个模板result.html ,如下所示:

{% extends "layout.html" %}
{% block body %}
<body>
  {% for line in result %}
    {{ line }}
  {% endfor %}
</body>
{% endblock %}

I would think the most straightforward way to do this is to create your page, and then use AJAX to make periodic requests to the server, and update the content on your page using the results. 我认为最直接的方法是创建页面,然后使用AJAX定期向服务器发出请求,并使用结果更新页面上的内容。 That might include implementing long polling to do this. 这可能包括实施长轮询来实现这一目标。

Any way you do this, you'll need to somehow make your function non-blocking, so that you can still serve requests while it operates. 无论如何,您都需要以某种方式使您的功能无阻塞,这样您仍然可以在操作时提供请求。 You could manually write a function that serves a request if there is one waiting and otherwise continues running the next "chunk" of the function. 如果有一个请求,您可以手动编写一个服务请求的函数,否则继续运行该函数的下一个“块”。 That would involve decomposing your function into small parts, so that you can dispatch them as needed. 这将涉及将您的功能分解为小部分,以便您可以根据需要调度它们。

A better approach might be to use threading or multiprocessing, depending on whether your function is bound by IO or CPU usage. 更好的方法可能是使用线程或多处理,具体取决于您的函数是否受IO或CPU使用的约束。

Do you have any plan to use WebSocket? 你有计划使用WebSocket吗? if so, you can refer: Websocket with Flask and Gevent 如果是这样,你可以参考: 使用Flask和Gevent的Websocket

You can use meta refresh in one of the template 您可以在其中一个模板中使用元刷新

meta http-equiv="refresh" content="5" meta http-equiv =“refresh”content =“5”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM