请用python实现程序在前端网页上点击按钮则开始执行ping 1111 并把每一行结果输出到网页上
要实现在前端网页上点击按钮后执行命令并将结果输出到网页上,你可以使用Python的Flask库来创建一个简单的Web应用,并使用subprocess库来执行系统命令。
首先,确保你已经安装了Flask库和subprocess库。你可以使用以下命令来安装它们:
pip install flask
接下来,创建一个名为app.py的Python文件,并将以下代码复制到文件中:
from flask import Flask, render_template, request
import subprocess
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/ping', methods=['POST'])
def ping():
result = subprocess.run(['ping', '1.1.1.1'], capture_output=True, text=True)
output = result.stdout.splitlines()
return render_template('index.html', output=output)
if __name__ == '__main__':
app.run(debug=True)
在上面的代码中,我们首先导入了Flask和subprocess库。然后,我们创建了一个Flask应用,并定义了两个路由。
index()函数用于渲染主页,它会呈现一个包含一个按钮的HTML页面(在后面的步骤中我们会创建这个页面)。
ping()函数是一个POST请求处理程序,它会执行ping 1.1.1.1命令,并将结果分割成行,然后将结果作为输出渲染到主页。
最后,我们通过运行app.run(debug=True)启动Flask应用。
接下来,创建一个名为templates的文件夹,并在其中创建一个名为index.html的HTML文件。将以下代码复制到index.html文件中:
<!DOCTYPE html>
<html>
<head>
<title>Ping Results</title>
</head>
<body>
<h1>Click the button to ping 1.1.1.1:</h1>
<form method="POST" action="/ping">
<input type="submit" value="Ping">
</form>
<h2>Ping Results:</h2>
{% if output %}
<ul>
{% for line in output %}
<li>{{ line }}</li>
{% endfor %}
</ul>
{% endif %}
</body>
</html>
在上面的代码中,我们创建了一个简单的HTML页面,其中包含一个表单和一个用于显示结果的无序列表。当点击按钮时,表单会向/ping路由发送一个POST请求,并将结果显示在无序列表中。
最后,打开终端,进入到包含app.py文件的目录,并运行以下命令启动Web应用:
python app.py
然后,打开浏览器,访问http://localhost:5000,你应该能够看到一个网页,其中包含一个按钮。当你点击按钮时,命令ping 1.1.1.1将会在服务器上执行,并将结果显示在网页上
原文地址: http://www.cveoy.top/t/topic/iSDL 著作权归作者所有。请勿转载和采集!