请用python实现一个网页的前后端实现在网页上显示2个按钮当点击按钮A时候后端执行命令ping 1111然后把结果在网页前端实时显示出来。当点击按钮B时后端停止这个进程
下面是一个使用Python实现的简单的网页前后端的例子,实现了在网页上显示两个按钮,点击按钮A时执行命令并将结果实时显示在网页上,点击按钮B时停止执行命令的进程。
前端代码(HTML):
<!DOCTYPE html>
<html>
<head>
<title>Button Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function sendCommand(command) {
$.ajax({
type: "POST",
url: "/execute",
data: {command: command},
success: function(response) {
$("#result").text(response);
}
});
}
function stopCommand() {
$.ajax({
type: "POST",
url: "/stop",
success: function(response) {
$("#result").text(response);
}
});
}
</script>
</head>
<body>
<button onclick="sendCommand('ping 1.1.1.1')">Button A</button>
<button onclick="stopCommand()">Button B</button>
<div id="result"></div>
</body>
</html>
后端代码(Python,使用Flask框架):
import subprocess
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/execute', methods=['POST'])
def execute_command():
command = request.form['command']
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = ''
for line in process.stdout:
line = line.decode('utf-8')
output += line
# 实时将输出发送给前端
yield line
process.wait()
if process.returncode == 0:
output += 'Command executed successfully'
else:
output += 'Command failed'
# 将最终结果发送给前端
yield output
@app.route('/stop', methods=['POST'])
def stop_command():
# TODO: 停止执行命令的进程
return 'Command stopped'
if __name__ == '__main__':
app.run()
请确保已安装Flask库,然后运行上述代码,在浏览器中访问http://localhost:5000即可看到网页上的按钮。点击按钮A时,会执行ping 1.1.1.1命令并将结果实时显示在网页上;点击按钮B时,会停止执行命令的进程。注意,stop_command()函数中的TODO部分需要根据具体需求来实现停止执行命令的进程的逻辑
原文地址: https://www.cveoy.top/t/topic/iSr4 著作权归作者所有。请勿转载和采集!