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.

Based on the answer here

I am trying to display output from 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() + '
\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)

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

解决方案

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() + '
\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')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值