Python Flask Web 应用实现命令行执行和停止 - 使用 subprocess 模块

本文介绍了如何使用 Python Flask 框架构建一个简单的 Web 应用,实现命令行程序的执行和停止功能,并通过 JSON 格式返回结果。代码示例使用了 subprocess 模块来执行命令,并处理了命令输出和错误信息。

代码示例

import subprocess
from flask import Flask, render_template, request, jsonify, make_response, redirect

app = Flask(__name__)
process = None

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

@app.route('/execute', methods=['POST'])
def execute():
    global process
    if request.form['action'] == 'start':
        if process is not None and process.poll() is None:
            # 如果进程正在运行,则不执行新的命令
            return jsonify({'output': '进程正在运行,请先停止'})  
        process = subprocess.Popen(['ping', '1.1.1.1'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        output, error = process.communicate()
        return jsonify({'output': output.decode('utf-8')})
    elif request.form['action'] == 'stop':
        if process is not None and process.poll() is None:
            # 如果进程正在运行,则停止进程
            process.terminate()
            process.wait()
            process = None
        return jsonify({'output': '进程已停止'})
    else:
        return make_response(jsonify({'error': '无效的动作'}), 400)

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

代码说明

  1. 导入必要的模块: subprocess 模块用于执行命令,Flask 模块用于构建 Web 应用,其他模块用于处理请求和响应。
  2. 定义全局变量: process 用于存储执行的命令进程。
  3. 定义路由: / 路由用于显示首页,/execute 路由用于处理执行和停止命令的请求。
  4. 处理执行请求: 当收到 start 动作时,代码会检查是否有进程正在运行。如果没有,则使用 subprocess.Popen 执行命令,并使用 process.communicate() 获取命令的输出和错误信息。最后,将输出作为 JSON 数据返回给前端。
  5. 处理停止请求: 当收到 stop 动作时,代码会检查是否有进程正在运行。如果有,则使用 process.terminate() 停止进程,并使用 process.wait() 等待进程结束。最后,将提示信息作为 JSON 数据返回给前端。

前端代码

<!DOCTYPE html>
<html>
<head>
    <title>命令行执行</title>
</head>
<body>
    <h1>命令行执行</h1>
    <button id='start'>启动</button>
    <button id='stop'>停止</button>
    <div id='output'></div>

    <script>
        const startButton = document.getElementById('start');
        const stopButton = document.getElementById('stop');
        const outputDiv = document.getElementById('output');

        startButton.addEventListener('click', () => {
            fetch('/execute', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: 'action=start'
            })
            .then(response => response.json())
            .then(data => {
                outputDiv.textContent = data.output;
            })
            .catch(error => console.error(error));
        });

        stopButton.addEventListener('click', () => {
            fetch('/execute', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: 'action=stop'
            })
            .then(response => response.json())
            .then(data => {
                outputDiv.textContent = data.output;
            })
            .catch(error => console.error(error));
        });
    </script>
</body>
</html>

总结

本文提供了一个简单的示例,演示了如何使用 Python Flask 框架构建 Web 应用,实现命令行程序的执行和停止功能,并通过 JSON 格式返回结果。您可以根据实际需要对代码进行扩展,例如添加更多命令、增加错误处理机制等。

Python Flask Web 应用实现命令行执行和停止 - 使用 subprocess 模块

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

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