相关疑难解决方法(0)

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

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

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

我需要在函数中做什么?

我需要在模板中做什么?

编辑:

我正在尝试使用Markus Unterwaditzer的代码和模板.

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

{% autoescape false %}

{{word}}

{% endautoescape %}

{% endblock %}
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

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

python jinja2 flask python-2.7

9
推荐指数
2
解决办法
2万
查看次数

如何根据 HTTP 请求使用 Python 和 Flask 执行 shell 命令并流输出?

在这篇文章之后,我可以将tail -f日志文件发送到网页:

from gevent import sleep
from gevent.wsgi import WSGIServer
import flask
import subprocess

app = flask.Flask(__name__)

@app.route('/yield')
def index():
    def inner():
        proc = subprocess.Popen(
                ['tail -f ./log'],
                shell=True,
                stdout=subprocess.PIPE
                )
        for line in iter(proc.stdout.readline,''):
            sleep(0.1)
            yield line.rstrip() + '<br/>\n'

    return flask.Response(inner(), mimetype='text/html')

http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()
Run Code Online (Sandbox Code Playgroud)

这种方法有两个问题。

  1. tail -f log关闭网页后,该过程将持续存在。访问http://localhost:5000/yield n 次后会有 n 个 tail 进程
  2. 一次只能有1个客户端访问http://localhost:5000/yield

我的问题是,是否可以让flask在有人访问页面时执行shell命令,并在客户端关闭页面时终止该命令?就像Ctrl+C之后tail -f log。如果没有,还有哪些替代方案?为什么我一次只能有 1 个客户端访问该页面?

注意:我正在研究启动/停止任意 shell 命令的一般方法,而不是特别尾随文件

python linux subprocess flask

2
推荐指数
1
解决办法
5425
查看次数

标签 统计

flask ×2

python ×2

jinja2 ×1

linux ×1

python-2.7 ×1

subprocess ×1