2013-02-26 63 views
17

Tôi muốn có thể truy cập một trang web và nó sẽ chạy một hàm python và hiển thị tiến trình trong trang web.Làm thế nào để liên tục hiển thị đầu ra Python trong một trang web?

Vì vậy, khi bạn truy cập trang web, bạn có thể thấy đầu ra của tập lệnh như thể bạn đã chạy nó từ dòng lệnh.

Dựa trên câu trả lời ở đây

How to continuously display python output in a webpage?

Tôi cố gắng để hiển thị đầu ra từ PYTHON

Tôi cố gắng để sử dụng mã Markus Unterwaditzer với một chức năng 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) 

Và nó chạy nhưng tôi không thấy gì trong trình duyệt.

Trả lời

20

Xin chào bạn có vẻ như bạn không muốn gọi hàm thử nghiệm, nhưng quá trình dòng lệnh thực tế cung cấp đầu ra. Cũng tạo ra một iterable từ proc.stdout.readline hoặc một cái gì đó. Ngoài ra bạn nói từ Python mà tôi quên bao gồm rằng bạn nên chỉ cần kéo bất kỳ mã python bạn muốn trong một subprocess và đặt nó trong một tập tin riêng biệt.

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') 
+0

Rất tiếc tôi đã thay đổi máy chủ để nó hoạt động trong môi trường âm hộ của tôi. –

+0

OMG, tôi đã thử rất nhiều thứ để làm việc này và đây là điều duy nhất đã làm! – JeffThompson

+0

Làm cách nào để chuyển Phản hồi cho một điểm cụ thể trong mẫu? – JeffThompson

0

Dưới đây là một giải pháp cho phép bạn dòng sản lượng subprocess & tải nó tĩnh sau khi thực tế sử dụng cùng một mẫu (giả định rằng hồ sơ tiến trình con của bạn đó là đầu ra riêng vào một tập tin, nếu không, sau đó ghi quá trình đầu ra vào một tập tin log là trái như một bài tập cho người đọc)

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()) 

bằng cách này bạn sẽ có được một mẫu phù hợp sử dụng cả hai trong thời gian chạy ban đầu của lệnh (qua POST) và trong quá trình phục vụ tĩnh của lưu logfile sau khi thực tế.

Các vấn đề liên quan