跳至正文

使用python执行命令行命令

import subprocess

class CommandLineExecutor:
    def execute_command(self, command):
        try:
            # 使用subprocess执行命令
            process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            stdout, stderr = process.communicate()

            # 检查命令的返回代码
            if process.returncode == 0:
                return {
                    "success": True,
                    "stdout": stdout.decode("utf-8"),
                    "stderr": stderr.decode("utf-8")
                }
            else:
                return {
                    "success": False,
                    "stdout": stdout.decode("utf-8"),
                    "stderr": stderr.decode("utf-8")
                }
        except Exception as e:
            return {
                "success": False,
                "stderr": str(e)
            }

只需要输入相应的command就可以。