我希望能够访问一个网页,它会运行一个 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)
它运行但我在浏览器中看不到任何内容。
请您参考如下方法:
嗨,您似乎不想调用测试函数,而是调用提供输出的实际命令行进程。还可以从 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')