Python网页前后端交互:实时显示Ping命令结果
本文将介绍如何使用 Python Flask 框架实现一个简单的网页应用,该应用可以实时显示 Ping 命令的执行结果。
用户可以通过网页上的按钮触发 Ping 命令的执行,并将结果实时显示在网页上。同时,用户也可以通过另一个按钮停止 Ping 命令的执行进程。
代码示例
from flask import Flask, render_template, request
from subprocess import Popen, PIPE
import threading
app = Flask(__name__)
process = None
output = ""
def run_command(command):
global process, output
process = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)
for line in iter(process.stdout.readline, b''):
output += line.decode()
process.stdout.close()
@app.route('/')
def index():
return render_template('index.html', output=output)
@app.route('/start')
def start():
global output
output = ""
command = 'ping 1.1.1.1'
threading.Thread(target=run_command, args=(command,)).start()
return 'Command started'
@app.route('/stop')
def stop():
global process
if process is not None:
process.terminate()
return 'Command stopped'
else:
return 'No command running'
if __name__ == '__main__':
app.run()
代码解释
- Flask框架: 使用 Flask 框架创建一个简单的 Web 应用。
index函数: 渲染一个名为index.html的模板,其中会将output变量传递给模板进行显示。start函数: 点击按钮 A 时被调用,创建一个新的线程,并在该线程中执行命令ping 1.1.1.1。命令的输出会被存储在output变量中,然后在模板中进行显示。stop函数: 点击按钮 B 时被调用,它会终止之前创建的进程。
模板文件
确保你的代码中存在一个名为 index.html 的模板文件,用于显示网页内容。模板文件的内容可以如下所示:
<!DOCTYPE html>
<html>
<head>
<title>Ping Result</title>
</head>
<body>
<h1>Ping Result:</h1>
<pre>{{ output }}</pre>
<button onclick="location.href='/start'">Start</button>
<button onclick="location.href='/stop'">Stop</button>
</body>
</html>
运行程序
运行这个代码后,访问 http://localhost:5000,你应该能够看到一个显示按钮的网页。点击按钮 A 会执行命令并将结果实时显示在网页上,点击按钮 B 会停止进程。
总结
本例展示了如何使用 Python Flask 框架实现一个简单的网页应用,通过按钮触发 Ping 命令执行,并在网页上实时显示结果。同时提供停止进程功能。你可以在此基础上进行扩展,例如添加更多命令、错误处理、用户认证等功能。
原文地址: https://www.cveoy.top/t/topic/qysf 著作权归作者所有。请勿转载和采集!