如何在不使用 flask 刷新浏览器的情况下将 python 脚本的动态输出显示/重定向到 html 页面

问题描述 投票:0回答:0

假设我有一个动态生成输出到 linux 终端的 python 脚本,我想使用 python flask 在网页上动态显示相同的输出,我需要在运行 python 脚本时在网页上获得与 linux 终端相同的实时输出

脚本.py

import time

while True:
    print("Hello, world!")
    time.sleep(1) # wait for 1 second before printing again

app.py

from flask import Flask, render_template
from flask_socketio import SocketIO, emit
import subprocess
from threading import Timer

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

@socketio.on('connect')
def test_connect():
    print('Client connected')

@socketio.on('disconnect')
def test_disconnect():
    print('Client disconnected')

@app.route('/')
def index():
    return render_template('index.html')

@socketio.on('run_script')
def run_script():
    p = subprocess.Popen(['python3', 'script.py'], stdout=subprocess.PIPE)

    def kill_proc():
        p.kill()
        print('Script process killed')

    t = Timer(60.0, kill_proc)  # Set a timeout of 60 seconds
    t.start()

    while True:
        output = p.stdout.readline().decode('utf-8')
        if output == '' and p.poll() is not None:
            break
        emit('script_output', {'data': output})

    t.cancel()

if __name__ == '__main__':
    socketio.run(app)

index.html

<!doctype html>
<html>
  <head>
    <title>Dynamically display script output with Flask-SocketIO</title>
  </head>
  <body>
    <button id="run-script">Run script</button>
    <div id="output"></div>

    <script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/4.3.2/socket.io.min.js"></script>
    <script type="text/javascript">
      var socket = io.connect('http://' + document.domain + ':' + location.port);
      socket.on('script_output', function(data) {
        var output = document.getElementById('output');
        output.innerHTML += data.data + '<br>';
      });
      document.getElementById('run-script').onclick = function() {
        socket.emit('run_script');
      };
    </script>
  </body>
</html>

以上文件是我试过的,但在浏览器上没有得到任何响应

python html flask socket.io subprocess
© www.soinside.com 2019 - 2024. All rights reserved.