请用实现一个系统该系统有一个网页作为输入和输出网页上有2个按钮点击A按钮启动一个进程运行如下命令iperf3 -s -p 1111并把输出结果实时显示到网页中。点击按钮B时停止这个命令。以下程序出错了找不到indexhtml
出现找不到index.html的错误,可能是因为程序没有正确指定网页文件的路径。请确保程序中的路径是正确的,并且index.html文件存在于指定路径中。
以下是一个示例程序,用于实现一个具有两个按钮的网页,点击A按钮启动命令并实时显示输出结果,点击B按钮停止命令。
import subprocess
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/start', methods=['POST'])
def start_command():
process = subprocess.Popen(['iperf3', '-s', '-p', '1111'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
# 将输出结果发送到网页
socketio.emit('message', {'data': output.decode('utf-8')}, namespace='/test')
return 'Command started'
@app.route('/stop', methods=['POST'])
def stop_command():
# 停止进程
process.terminate()
return 'Command stopped'
if __name__ == '__main__':
app.run()
index.html文件的内容如下:
<!DOCTYPE html>
<html>
<head>
<title>Command Control</title>
</head>
<body>
<h1>Command Control</h1>
<button onclick="startCommand()">Start</button>
<button onclick="stopCommand()">Stop</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
<script>
var socket = io.connect('http://' + document.domain + ':' + location.port + '/test');
socket.on('message', function(data) {
// 在网页中显示输出结果
document.getElementById('output').innerHTML += data.data + '<br>';
});
function startCommand() {
fetch('/start', { method: 'POST' });
}
function stopCommand() {
fetch('/stop', { method: 'POST' });
}
</script>
<div id="output"></div>
</body>
</html>
确保index.html文件与Python程序在同一目录下,并且运行程序后通过访问http://localhost:5000/可以打开网页。点击Start按钮将启动命令,并将输出结果实时显示在网页上,点击Stop按钮将停止命令的执行
原文地址: http://www.cveoy.top/t/topic/iRKN 著作权归作者所有。请勿转载和采集!