这个错误是因为浏览器在请求网页时会发送一个请求获取favicon.ico,而你的后端代码没有处理这个请求导致报错。可以忽略这个错误,或者添加一个处理favicon.ico请求的代码。

以下是一个简单的实现示例:

from flask import Flask, render_template, request
import subprocess

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/command', methods=['POST'])
def execute_command():
    command = request.form['command']
    if command == 'A':
        start_ping()
    elif command == 'B':
        stop_ping()
    return ''

def start_ping():
    global ping_process
    ping_process = subprocess.Popen(['ping', '1.1.1.1'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

def stop_ping():
    ping_process.terminate()

if __name__ == '__main__':
    app.run(debug=True)

在上面的示例中,我们使用了Flask框架来实现网页的前后端。在前端的HTML文件中,我们定义了两个按钮,分别对应命令A和B。当点击按钮A时,会向后端发送一个POST请求,后端会执行start_ping()函数来启动ping命令,并将结果实时显示在网页上。当点击按钮B时,会发送一个POST请求,后端会执行stop_ping()函数来终止ping命令。

同时,你还需要在同级目录下创建一个名为index.html的HTML文件,内容如下:

<!DOCTYPE html>
<html>
<head>
    <title>Button Example</title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <button id="buttonA" onclick="executeCommand('A')">Button A</button>
    <button id="buttonB" onclick="executeCommand('B')">Button B</button>
    <div id="output"></div>

    <script type="text/javascript">
        function executeCommand(command) {
            $.ajax({
                url: '/command',
                type: 'POST',
                data: {command: command},
                success: function(response) {
                    if (command === 'A') {
                        startOutput();
                    } else if (command === 'B') {
                        stopOutput();
                    }
                }
            });
        }

        function startOutput() {
            var outputDiv = $('#output');
            var source = new EventSource('/output');
            source.onmessage = function(event) {
                outputDiv.append(event.data + '<br>');
                outputDiv.scrollTop(outputDiv[0].scrollHeight);
            };
        }

        function stopOutput() {
            var source = new EventSource('/output');
            source.close();
        }
    </script>
</body>
</html>

这里使用了jQuery库来处理前端的Ajax请求,并通过EventSource来实现实时显示命令输出结果。

在运行Python脚本后,打开浏览器访问http://localhost:5000,即可看到具有两个按钮的网页。点击按钮A会启动ping命令并将结果实时显示在网页上,点击按钮B会停止ping命令

请用python实现一个网页的前后端实现在网页上显示2个按钮当点击按钮A时候后端执行命令ping 1111然后把结果在网页前端实时显示出来。当点击按钮B时后端停止这个进程下面的程序运行出错了GET faviconico HTTP11 404 -

原文地址: https://www.cveoy.top/t/topic/iSsd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录