请用python实现一个网页的前后端实现在网页上显示2个按钮当点击按钮A时候后端执行命令ping 1111然后把结果在网页前端实时显示出来。当点击按钮B时后端停止这个进程下面的程序运行出错了GET HTTP11 500 -
这个错误是因为程序中的某个地方出现了错误,导致服务器无法正常处理请求。要解决这个问题,我们需要进一步检查代码并修复错误。
以下是一个简单的示例,展示如何使用Python实现一个网页的前后端,实现在网页上显示两个按钮,点击按钮A时执行命令并将结果实时显示出来,点击按钮B时停止进程。
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框架来创建一个简单的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>
这个模板文件定义了一个标题和一个<pre>标签,用于显示命令的输出结果。两个按钮分别绑定到/start和/stop路径。
运行这个代码后,访问http://localhost:5000,你应该能够看到一个显示按钮的网页。点击按钮A会执行命令并将结果实时显示在网页上,点击按钮B会停止进程
原文地址: https://www.cveoy.top/t/topic/iSsn 著作权归作者所有。请勿转载和采集!