• 【python】subprocess用法示例


    当然,下面是一些使用 Python subprocess 模块的示例:

    1. 运行命令并捕获输出

    import subprocess
    # 运行 'ls' 命令并捕获输出
    result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    # 获取命令的输出和错误信息
    output = result.stdout
    error = result.stderr
    print("输出:", output)
    if error:
        print("错误:", error)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    2. 检查命令是否成功执行

    import subprocess
    # 检查 'ls' 命令是否成功执行
    try:
        result = subprocess.check_call(['ls', 'nonexistent_file'])
        print("命令成功执行")
    except subprocess.CalledProcessError as e:
        print("命令执行错误,退出状态码:", e.returncode)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    3. 运行命令并捕获输出,同时发送输出到控制台

    import subprocess
    # 运行 'ls' 命令,将输出直接打印到控制台
    result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True)
    print(result.stdout)
    
    • 1
    • 2
    • 3
    • 4

    4. 使用 Popen 类

    import subprocess
    # 使用 Popen 类运行 'ls' 命令
    p = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    output, error = p.communicate()
    print("输出:", output)
    if error:
        print("错误:", error)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    5. 发送输入到命令

    import subprocess
    # 运行 'cat' 命令,并发送输入 'Hello, World!'
    p = subprocess.Popen(['cat'], stdin=subprocess.PIPE, text=True)
    p.communicate(input='Hello, World!')
    
    • 1
    • 2
    • 3
    • 4

    6. 捕获环境和返回码

    import subprocess
    # 运行 'ls' 命令,并捕获环境变量和返回码
    result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env={'MY_ENV_VAR': '123'})
    print("退出状态码:", result.returncode)
    print("环境变量:", result.env)
    
    • 1
    • 2
    • 3
    • 4
    • 5

    这些示例展示了 subprocess 模块的一些基本用法。您可以根据需要调整命令、输入、输出和错误处理方式。
    当然,这里有一些其他使用 subprocess 模块的示例:

    7. 调用 git 命令

    import subprocess
    # 获取当前分支名
    try:
        branch = subprocess.check_output(['git', 'rev-parse', '--abbreviate', '--current', 'HEAD'],
                                         stderr=subprocess.STDOUT, text=True).strip()
        print(f"当前分支: {branch}")
    except subprocess.CalledProcessError as e:
        print(f"无法获取分支信息:{e.output}")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    8. 编译 C 代码

    import subprocess
    # 编译 C 代码
    try:
        compile_result = subprocess.check_call(['gcc', '-o', 'program', 'program.c'],
                                               stderr=subprocess.STDOUT, text=True)
        print(f"编译成功,退出状态码:{compile_result}")
    except subprocess.CalledProcessError as e:
        print(f"编译失败:{e.output}")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    9. 克隆 Git 仓库

    import subprocess
    # 克隆 Git 仓库
    try:
        clone_result = subprocess.check_output(['git', 'clone', 'https://github.com/user/repo.git'],
                                               stderr=subprocess.STDOUT, text=True)
        print(f"克隆成功:{clone_result}")
    except subprocess.CalledProcessError as e:
        print(f"克隆失败:{e.output}")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    10. 检查 Python 环境

    import subprocess
    # 检查 Python 环境
    try:
        py_version = subprocess.check_output(['python', '--version'],
                                             stderr=subprocess.STDOUT, text=True).strip()
        print(f"Python 版本:{py_version}")
    except subprocess.CalledProcessError as e:
        print(f"无法检查 Python 版本:{e.output}")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    11. 使用管道

    import subprocess
    # 使用管道将一个命令的输出作为另一个命令的输入
    result = subprocess.run(['wc', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    file_count = int(result.stdout.strip())
    try:
        git_status = subprocess.check_output(['git', 'status'], stdin=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
        print(f"文件数:{file_count}")
        print(f"Git 状态:{git_status}")
    except subprocess.CalledProcessError as e:
        print(f"命令执行错误:{e.output}")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    12. 捕获实时输出

    import subprocess
    # 运行一个命令,并实时捕获输出
    process = subprocess.Popen(['tail', '-f', '/var/log/syslog'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    while True:
        line = process.stdout.readline()
        if line == '' and process.poll() is not None:
            break
        if line:
            print(line.strip())
    # 等待进程结束
    process.wait()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    这些示例展示了 subprocess 模块在不同场景下的应用,包括调用系统工具、编译代码、克隆仓库、检查 Python 版本、使用管道以及实时捕获命令输出。根据您的具体需求,可以调整命令、输入、输出和错误处理方式。

  • 相关阅读:
    实现分布式下的全局唯一ID
    【计算机网络笔记】分组交换中的报文交付时间计算例题
    校园安防监控系统升级改造方案:如何实现设备利旧上云与AI视频识别感知?
    智能优化算法 | Matlab实现ABC人工蜂群优化算法
    基于javaweb的农业信息管理系统(java+ssm+jsp+js+html+mysql)
    【微软漏洞分析】一个未修复的问题 MSRC-20706 - Windows 7:NtPowerInformation 中的管理员检查绕过
    PCA主成分分析法浅理解
    「Verilog学习笔记」数据选择器实现逻辑电路
    @PropertySource读取自定义配置
    [实践应用] 深度学习之损失函数
  • 原文地址:https://blog.csdn.net/qq_41604569/article/details/136352386