你可以使用Python的subprocess模块来执行命令,并将输出实时显示在网页上。以下是一个简单的示例:

index.html:

<!DOCTYPE html>
<html>
<head>
  <title>Button Example</title>
</head>
<body>
  <h1>Button Example</h1>
  <button id="btnA">按钮A</button>
  <button id="btnB">按钮B</button>
  <pre id="output"></pre>

  <script>
    const btnA = document.getElementById('btnA');
    const btnB = document.getElementById('btnB');
    const output = document.getElementById('output');
    let process;

    btnA.addEventListener('click', () => {
      output.textContent = '命令已执行\n';
      process = new Process('ping 1.1.1.1');
      process.start();
    });

    btnB.addEventListener('click', () => {
      if (process) {
        process.stop();
        output.textContent += '进程已停止\n';
      }
    });

    class Process {
      constructor(command) {
        this.command = command;
        this.process = null;
      }

      start() {
        this.process = new Worker('/execute');
        this.process.onmessage = (event) => {
          output.textContent += event.data;
        };
        this.process.postMessage(this.command);
      }

      stop() {
        this.process.terminate();
        this.process = null;
      }
    }
  </script>
</body>
</html>

app.py:

from flask import Flask, render_template, request, jsonify
from threading import Thread
import subprocess

app = Flask(__name__)

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

@app.route('/execute', methods=['POST'])
def execute():
    command = request.get_data().decode('utf-8')
    process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
    for line in iter(process.stdout.readline, b''):
        line = line.decode('utf-8')
        # 将命令输出发送给前端
        thread = Thread(target=send_message, args=(line,))
        thread.start()
    process.wait()
    return jsonify({'success': True})

def send_message(message):
    with app.app_context():
        app.response_class(
            response=message,
            status=200,
            mimetype='text/plain'
        )

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

首先,需要安装Flask模块:

pip install Flask

然后,在命令行中执行以下命令来启动应用:

python app.py

接下来,打开浏览器并访问http://localhost:5000,你将看到一个网页上有两个按钮。当你点击按钮A时,它会执行ping 1.1.1.1命令,并将实时输出显示在网页上。当你点击按钮B时,它会停止命令的执行。

注意:这个示例仅供参考,实际应用中需要考虑安全性和错误处理等因素

请用python实现一个网页的前后端实现在网页上显示2个按钮当点击按钮A时候执行命令ping 1111然后把实时的输出在网页前端显示出来。当点击按钮B时后端停止这个进程以下程序只显示了命令已执行并没有ping命令的输出

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

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