我希望能够访问一个网页,它将运行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)
它会运行,但我在浏览器中看不到任何内容。
发布于 2013-03-12 14:04:06
Hi看起来你并不想调用一个测试函数,而是一个提供输出的实际命令行进程。也可以从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')
发布于 2016-02-26 07:46:36
这里有一个解决方案,它允许您流式传输子流程输出,并使用相同的模板在事后静态地加载它(假设子流程将自己的输出记录到一个文件中;如果没有,则将流程输出记录到日志文件中作为练习留给读者)
from flask import Response, escape
from yourapp import app
from subprocess import Popen, PIPE, STDOUT
SENTINEL = '------------SPLIT----------HERE---------'
VALID_ACTIONS = ('what', 'ever')
def logview(logdata):
"""Render the template used for viewing logs."""
# Probably a lot of other parameters here; this is simplified
return render_template('logview.html', logdata=logdata)
def stream(first, generator, last):
"""Preprocess output prior to streaming."""
yield first
for line in generator:
yield escape(line.decode('utf-8')) # Don't let subproc break our HTML
yield last
@app.route('/subprocess/<action>', methods=['POST'])
def perform_action(action):
"""Call subprocess and stream output directly to clients."""
if action not in VALID_ACTIONS:
abort(400)
first, _, last = logview(SENTINEL).partition(SENTINEL)
path = '/path/to/your/script.py'
proc = Popen((path,), stdout=PIPE, stderr=STDOUT)
generator = stream(first, iter(proc.stdout.readline, b''), last)
return Response(generator, mimetype='text/html')
@app.route('/subprocess/<action>', methods=['GET'])
def show_log(action):
"""Show one full log."""
if action not in VALID_ACTIONS:
abort(400)
path = '/path/to/your/logfile'
with open(path, encoding='utf-8') as data:
return logview(logdata=data.read())
这样,您就可以获得一个在命令初始运行(通过POST)和事后静态处理保存的日志文件期间使用的一致模板。
https://stackoverflow.com/questions/15092961
复制相似问题