import subprocessfrom flask import Flask render_template request jsonify Responseapp = Flask__name__ template_folder=Dpythonwebpingprocess = Noneoutput_list = stream_list = approutedef index return
您可以尝试使用SocketIO来实现实时输出到网页上。首先,需要安装flask-socketio库:
pip install flask-socketio
然后,修改代码如下:
import subprocess
from flask import Flask, render_template, request, jsonify
from flask_socketio import SocketIO
app = Flask(__name__, template_folder='D:\\python\\webping')
app.config['SECRET_KEY'] = 'secret_key'
socketio = SocketIO(app)
process = None
@app.route('/')
def index():
return render_template('index.html')
@app.route('/start', methods=['POST'])
def start():
global process
if process:
return jsonify({'message': 'Command already running.'})
process = subprocess.Popen(['ping', '-t', '114.114.114.114'], stdout=subprocess.PIPE, universal_newlines=True)
def stream():
i = 0
while process and process.poll() is None:
output = process.stdout.readline().strip()
i+=1
print(i,output)
socketio.emit('stream_output', output)
socketio.start_background_task(stream)
return jsonify({'message': 'Command started.'})
@app.route('/stop', methods=['POST'])
def stop():
global process
if process:
process.terminate()
process = None
return jsonify({'message': 'Command stopped.'})
else:
return jsonify({'message': 'No command running.'})
if __name__ == '__main__':
socketio.run(app)
然后,在index.html文件中添加以下代码:
<!DOCTYPE html>
<html>
<head>
<title>Web Ping</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.1/socket.io.js"></script>
</head>
<body>
<h1>Web Ping</h1>
<button id="start-button">Start</button>
<button id="stop-button">Stop</button>
<div id="output"></div>
<script>
var socket = io();
socket.on('stream_output', function(output) {
var outputDiv = document.getElementById('output');
outputDiv.innerHTML += output + '<br>';
});
document.getElementById('start-button').addEventListener('click', function() {
fetch('/start', {method: 'POST'})
.then(response => response.json())
.then(data => console.log(data));
});
document.getElementById('stop-button').addEventListener('click', function() {
fetch('/stop', {method: 'POST'})
.then(response => response.json())
.then(data => console.log(data));
});
</script>
</body>
</html>
这样,当点击"Start"按钮时,会启动ping命令并将输出实时显示在网页上;点击"Stop"按钮时,会停止ping命令
原文地址: http://www.cveoy.top/t/topic/iSEj 著作权归作者所有。请勿转载和采集!