用python实现类AI自动执行终端指令

你是否曾好奇 AI 如何自动执行终端指令,无需人工干预?

又或者,如何实现自动化调用系统命令,让程序代替人工完成重复性操作?

如果你希望通过 Python 实现这些功能,那么 subprocess 模块将是你的得力助手。

subprocess 简介

subprocess 是 Python 中用于构建命令行交互和自动化任务的核心模块之一。它无需额外安装,是 Python 标准库的一部分,开箱即用。

示例

python 复制代码
import subprocess

# 查看当前目录
result = subprocess.run(["cmd", "/c", "cd"])
print(f"返回码: {result.returncode}")

说明run() 是执行命令的核心函数,参数以列表形式传入,每个元素代表命令的一部分。执行结果可通过返回值获取。

基本用法

掌握以下几种典型用法,你就能应对大部分自动化场景:

python 复制代码
import subprocess

# 1. 执行命令并获取返回码
result = subprocess.run(["cmd", "/c", "cd"])
print(f"返回码: {result.returncode}")

# 2. 捕获命令输出
result = subprocess.run(["cmd", "/c", "cd"],
                       capture_output=True,
                       text=True)
print(f"输出内容: {result.stdout}")

# 3. 设置超时控制
try:
    result = subprocess.run(["powershell", "sleep", "10"],
                          timeout=2,  # 2秒后超时
                          capture_output=True)
except subprocess.TimeoutExpired:
    print("命令执行超时")

# 4. 严格检查执行结果(失败时抛出异常)
result = subprocess.run(["cmd", "/c", "cd", "nonexistent"],
                       capture_output=True,
                       text=True,
                       check=True)  # 非零返回码将触发异常

执行效果

进阶技巧

管道操作(Pipe)

管道可将前一个命令的输出作为下一个命令的输入,例如 A | B 表示将 A 的输出传递给 B。

python 复制代码
netstat = subprocess.Popen(["netstat", "-ano"], stdout=subprocess.PIPE)
find = subprocess.Popen(
    ["findstr", "127.0.0.1:6379"],
    stdin=netstat.stdout,
    stdout=subprocess.PIPE,
    text=True
)
netstat.stdout.close()  # 允许 netstat 正常结束
output = find.communicate()[0]
print(output)

💡 提示:管道操作本质上相当于串联执行多个命令,也可通过多次调用 subprocess.run() 实现。

与交互式程序通信

以下示例演示如何通过 subprocess 调用 Python 解释器并执行动态指令:

python 复制代码
def interactive_program():
    """与交互式程序通信"""
    process = subprocess.Popen(
        ["python", "-i"],  # 启动交互式 Python 环境
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True
    )

    # 发送指令序列
    commands = ["print('Hello')", "1 + 1", "exit()"]

    for cmd in commands:
        process.stdin.write(cmd + "\n")
        process.stdin.flush()

    # 获取执行结果
    output, error = process.communicate()
    return output

print(interactive_program())

封装为可复用函数

将常用逻辑封装成函数,可大幅提升代码的可维护性和复用性:

python 复制代码
import subprocess
from typing import List, Optional, Tuple

def run_command(
    cmd: List[str],
    cwd: Optional[str] = None,
    env: Optional[dict] = None,
    timeout: Optional[int] = 30,
    check: bool = True
) -> Tuple[int, str, str]:
    """
    通用命令执行函数

    Args:
        cmd: 命令及参数列表
        cwd: 工作目录
        env: 环境变量
        timeout: 超时时间(秒)
        check: 是否在非零返回码时抛出异常

    Returns:
        (returncode, stdout, stderr)
    """
    try:
        result = subprocess.run(
            cmd,
            cwd=cwd,
            env=env,
            capture_output=True,
            text=True,
            timeout=timeout,
            check=check
        )
        return result.returncode, result.stdout, result.stderr

    except subprocess.TimeoutExpired as e:
        print(f"命令超时: {' '.join(cmd)}")
        return -1, "", f"Timeout after {timeout} seconds"

    except subprocess.CalledProcessError as e:
        print(f"命令执行失败: {' '.join(cmd)}")
        print(f"错误输出: {e.stderr}")
        return e.returncode, e.stdout, e.stderr

# 使用示例
returncode, stdout, stderr = run_command(
    ["docker", "ps", "-a"],
    timeout=10
)

好啦,今天的分享就到这里啦,感谢阅读,欢迎三连和关注咧!我们下期再见!🚀

相关推荐
前端程序猿之路2 小时前
AI大模型应用开发之容器化部署
人工智能·python·语言模型·云原生·eureka·ai编程·改行学it
码界奇点2 小时前
基于SpringBoot+Vue的新冠物资管理系统设计与实现
vue.js·spring boot·后端·spring·车载系统·毕业设计·源代码管理
风的归宿552 小时前
openresty监控
后端
创新技术阁2 小时前
CryptoAiAdmin项目数据库表自动创建和初始化
后端·python·fastapi
okseekw2 小时前
深入理解Java注解:从自定义到实战应用
java·后端
Blossom.1182 小时前
多模态视频理解实战:从0到1构建视频-文本对齐大模型
人工智能·python·深度学习·神经网络·重构·音视频·知识图谱
轻竹办公PPT2 小时前
2026 年年度工作计划 PPT:AI 自动生成方案横向对比
人工智能·python·powerpoint
执笔论英雄2 小时前
【RL】op_compute_log_probs 计算过程
人工智能·pytorch·python
毕设源码-邱学长2 小时前
【开题答辩全过程】以 基于SpringBoot的智能家具物联网平台的设计与实现为例,包含答辩的问题和答案
spring boot·后端·物联网