如何在网页中连续显示 Python 输出? [英] How to continuously display Python output in a Webpage?

查看:41
本文介绍了如何在网页中连续显示 Python 输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to be able to visit a webpage and it will run a python function and display the progress in the webpage.

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

So when you visit the webpage you can see the output of the script as if you ran it from the command line.

基于这里的答案

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

我正在尝试显示 PYTHON

我正在尝试将 Markus Unterwaditzer 的代码与 Python 函数结合使用.

I am trying to use Markus Unterwaditzer's code with a python function.

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/>
'
    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)

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

And it runs but I don't see anything in the browser.

推荐答案

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

Hi looks like you don't want to call a test function, but an actual command line process which provides output. Also create an iterable from proc.stdout.readline or something. Also you said from Python which I forgot to include that you should just pull any python code you want in a subprocess and put it in a separate file.

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/>
'

    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 输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆