Python subprocess 模块从入门到封神,20 + 实战案例吃透进程操作|建议直接收藏

张开发
2026/4/14 8:43:41 15 分钟阅读

分享文章

Python subprocess 模块从入门到封神,20 + 实战案例吃透进程操作|建议直接收藏
本文详细介绍 Python3subprocess 模块全套知识包括模块作用、核心函数、参数详解、进程控制、输出捕获、错误处理、超时设置、管道通信、安全规范与 20 可直接运行实战案例。所有示例均在代码中以注释形式标注预期输出无需运行即可直观查看适合零基础小白、运维、后端开发者快速掌握建议收藏反复阅读。前言在 Python 开发中执行系统命令、调用外部程序、处理进程输入输出、编写自动化运维脚本是极为常见的需求。传统的os.system()、os.popen()等方法功能单一、输出难以捕获、安全性较低而subprocess作为 Python 官方推荐的标准库完美替代了老旧模块提供统一、强大、安全的进程创建与管理能力支持 Windows/Linux/macOS 跨平台使用。本专栏带你从零基础入门系统掌握 subprocess 的所有用法从最简单的命令执行到复杂的管道通信、异步输出、进程管控全部用清晰案例讲解。无论你是编程新手、自动化爱好者、运维工程师还是后端开发人员都能快速上手写出稳定高效的进程管理代码。 前篇文章咱们讲解了 Python3 模块学习教程如果忘记了可以去重温一下不停的重复敲击基础代码有助于让你更加熟练掌握一门语言。今天咱们学习Python3 subprocess 模块全面实战教程下面开始吧在 Python 与系统交互的场景里subprocess 是绕不开的核心模块。它可以启动新进程、连接输入 / 输出 / 错误管道、获取返回值让你用 Python 轻松 “指挥” 操作系统。本文从基础到高级全覆盖讲解所有代码示例均内置注释式预期输出方便读者直接阅读学习。一、什么是 subprocess 模块subprocess是 Python3 内置的进程管理标准库无需额外安装直接导入即可使用。核心作用在 Python 程序中创建和控制子进程执行系统命令、exe/bat/sh 脚本、第三方软件捕获标准输出、标准错误、命令返回码支持管道、超时、参数传递、工作目录指定替代os.system()、os.popen()、commands等旧接口一句话总结subprocess 让 Python 具备操控系统进程、与系统深度交互的能力。二、subprocess 核心优势API 统一易用一套接口覆盖命令执行、流捕获、错误处理学习成本低。安全性更高支持列表传参有效避免 Shell 注入风险。控制粒度精细可设置超时、编码、环境变量、重定向流等。信息完整同时获取输出、错误、返回码便于业务逻辑判断。跨平台兼容一套代码可在 Windows、Linux、macOS 平稳运行。三、subprocess 核心函数Python3.5 及以上版本推荐使用优先级subprocess.run()官方首选阻塞执行功能最全subprocess.Popen()底层高级类支持异步、实时输出辅助函数call()、check_call()、check_output()四、subprocess.run () 用法详解4.1 语法结构python运行subprocess.run( args, stdoutNone, stderrNone, shellFalse, cwdNone, timeoutNone, checkFalse, textFalse, encodingNone )4.2 直接执行命令不捕获输出python运行import subprocess # 执行dir命令列出当前目录文件直接打印到控制台 subprocess.run([dir], shellTrue, textTrue, encodinggbk) # 预期输出控制台直接打印 # 驱动器 D 中的卷是 数据 # 目录 D:\source\py # 2026-04-13 15:00 DIR . # 2026-04-13 15:00 DIR .. # 2026-04-13 14:55 256 app.py4.3 捕获标准输出 stdoutpython运行import subprocess result subprocess.run( [ping, 127.0.0.1, -n, 2], stdoutsubprocess.PIPE, stderrsubprocess.PIPE, shellTrue, textTrue, encodinggbk ) print(返回码, result.returncode) # 输出返回码0 print(输出内容\n, result.stdout) # 输出内容 # 正在 Ping 127.0.0.1 具有 32 字节的数据: # 来自 127.0.0.1 的回复: 字节32 时间1ms TTL128 # 来自 127.0.0.1 的回复: 字节32 时间1ms TTL1284.4 捕获标准错误 stderrpython运行import subprocess result subprocess.run( [ipconfig, aaa], stdoutsubprocess.PIPE, stderrsubprocess.PIPE, shellTrue, textTrue, encodinggbk ) print(错误输出\n, result.stderr) # 错误输出 # 错误的参数或命令 - 请键入 ipconfig /? 查看用法4.5 合并 stdout 与 stderrpython运行import subprocess result subprocess.run( [dir, test123456], stdoutsubprocess.PIPE, stderrsubprocess.STDOUT, shellTrue, textTrue, encodinggbk ) print(result.stdout) # 输出 # 找不到文件4.6 命令超时处理python运行import subprocess try: subprocess.run([ping, 1.1.1.1, -n, 10], timeout3, shellTrue) except subprocess.TimeoutExpired: print(命令执行超时) # 输出命令执行超时4.7 checkTrue 失败抛异常python运行import subprocess try: subprocess.run([wrongcmd], shellTrue, checkTrue) except subprocess.CalledProcessError: print(命令执行失败) # 输出命令执行失败五、args 参数列表 vs 字符串安全重点5.1 列表形式推荐安全无注入python运行subprocess.run([ping, 127.0.0.1, -n, 2]) # 正常执行ping命令无安全风险5.2 字符串形式需 shellTruepython运行subprocess.run(ping 127.0.0.1 -n 2, shellTrue) # 执行结果同列表形式5.3 Shell 注入风险示例python运行# 危险写法禁止用于用户输入 user_input 127.0.0.1 del /s /q *.* subprocess.run(fping {user_input}, shellTrue) # 安全写法列表传参杜绝注入 subprocess.run([ping, user_input, -n, 1]) # 输出仅执行ping不会执行恶意命令六、常用便捷函数6.1 subprocess.call () 获取返回码python运行import subprocess code subprocess.call([dir], shellTrue) print(返回码, code) # 输出返回码06.2 subprocess.check_call () 失败抛异常python运行import subprocess try: subprocess.check_call([dir, nodir], shellTrue) except subprocess.CalledProcessError: print(执行失败) # 输出执行失败6.3 subprocess.check_output () 直接获取输出python运行import subprocess out subprocess.check_output([ipconfig], shellTrue, encodinggbk) print(out[:200]) # 输出前200字符 # Windows IP 配置 # 以太网适配器 以太网: # 连接特定的 DNS 后缀 . . . . . . . : # 本地链接 IPv6 地址. . . . . . . . : fe80::xxxx # IPv4 地址 . . . . . . . . . . . . : 192.168.1.100七、Popen 高级用法7.1 实时读取输出python运行import subprocess p subprocess.Popen( [ping, 127.0.0.1, -n, 3], stdoutsubprocess.PIPE, stderrsubprocess.PIPE, shellTrue, textTrue, encodinggbk ) for line in p.stdout: print(line.strip()) # 逐行输出 # 正在 Ping 127.0.0.1 具有 32 字节的数据: # 来自 127.0.0.1 的回复: 字节32 时间1ms TTL128 # 来自 127.0.0.1 的回复: 字节32 时间1ms TTL128 p.wait() print(返回码, p.returncode) # 输出返回码07.2 获取 PID 并终止进程python运行import subprocess p subprocess.Popen([notepad.exe], shellTrue) print(进程PID, p.pid) # 输出进程PID12340 p.terminate() print(进程已终止) # 输出进程已终止八、20 个完整实战案例内置注释输出python运行import subprocess # # 1. 基础执行 dir 命令 # def demo1(): subprocess.run([dir], shellTrue, textTrue, encodinggbk) # 输出当前目录所有文件列表 # # 2. 捕获 ping 输出 # def demo2(): res subprocess.run( [ping, 127.0.0.1, -n, 2], stdoutsubprocess.PIPE, stderrsubprocess.PIPE, shellTrue, textTrue, encodinggbk ) print(res.returncode) # 0 print(res.stdout) # 输出 ping 正常回显 # # 3. 捕获错误参数输出 # def demo3(): res subprocess.run( [ipconfig, aaa], stdoutsubprocess.PIPE, stderrsubprocess.PIPE, shellTrue, textTrue, encodinggbk ) print(res.stderr) # 输出错误的参数或命令 # # 4. 合并输出与错误流 # def demo4(): res subprocess.run( [dir, nonefile], stdoutsubprocess.PIPE, stderrsubprocess.STDOUT, shellTrue, textTrue, encodinggbk ) print(res.stdout) # 输出找不到文件 # # 5. 命令超时 # def demo5(): try: subprocess.run([ping, 1.1.1.1, -n, 10], timeout3, shellTrue) except subprocess.TimeoutExpired: print(超时) # 输出超时 # # 6. checkTrue 抛异常 # def demo6(): try: subprocess.run([wrong], shellTrue, checkTrue) except subprocess.CalledProcessError: print(失败) # 输出失败 # # 7. 获取 ipconfig 信息 # def demo7(): res subprocess.run( [ipconfig], stdoutsubprocess.PIPE, shellTrue, textTrue, encodinggbk ) print(res.stdout[:200]) # 输出IP配置信息 # # 8. 查看网络端口 netstat # def demo8(): res subprocess.run( [netstat, -ano], stdoutsubprocess.PIPE, shellTrue, textTrue, encodinggbk ) print(res.stdout[:300]) # 输出网络连接列表 # # 9. 安全传参执行 ping # def demo9(): ip 127.0.0.1 res subprocess.run( [ping, ip, -n, 1], stdoutsubprocess.PIPE, shellTrue, textTrue, encodinggbk ) print(res.stdout) # 输出一次ping结果 # # 10. call() 获取返回码 # def demo10(): code subprocess.call([dir], shellTrue) print(code) # 0 # # 11. check_call() 异常 # def demo11(): try: subprocess.check_call([dir, xx], shellTrue) except: print(失败) # 失败 # # 12. check_output() 输出 # def demo12(): out subprocess.check_output([ipconfig], shellTrue, encodinggbk) print(out[:150]) # 输出IP配置片段 # # 13. Popen 实时输出 # def demo13(): p subprocess.Popen( [ping, 127.0.0.1, -n, 3], stdoutsubprocess.PIPE, stderrsubprocess.PIPE, shellTrue, textTrue, encodinggbk ) for line in p.stdout: print(line.strip()) # 逐行打印ping结果 p.wait() print(p.returncode) # 0 # # 14. 获取进程 PID # def demo14(): p subprocess.Popen([notepad], shellTrue) print(p.pid) # 输出类似13579 p.terminate() # # 15. 主动终止进程 # def demo15(): p subprocess.Popen([ping, 127.0.0.1, -n, 5], shellTrue) p.terminate() print(已杀死) # 已杀死 # # 16. 指定工作目录 # def demo16(): subprocess.run([dir], shellTrue, cwdD:\\) # 输出 D 盘根目录文件列表 # # 17. 管道命令 tasklist|findstr # def demo17(): res subprocess.run( tasklist | findstr python, stdoutsubprocess.PIPE, shellTrue, textTrue, encodinggbk ) print(res.stdout) # 输出python进程信息 # # 18. 标准输入 stdin # def demo18(): p subprocess.Popen( [findstr, python], stdinsubprocess.PIPE, stdoutsubprocess.PIPE, shellTrue, textTrue ) out p.communicate(inputtest python\nabc\npython dev)[0] print(out) # 输出 # test python # python dev # # 19. 判断执行结果 # def demo19(): res subprocess.run([dir], shellTrue) print(成功 if res.returncode 0 else 失败) # 输出成功 # # 20. 执行 bat 脚本 # def demo20(): subprocess.run([test.bat], shellTrue) # 输出 test.bat 执行内容 if __name__ __main__: demo1()九、编码问题说明Windows 中文系统必须使用encodinggbkLinux / macOS使用encodingutf-8不指定编码会返回 bytes 类型需手动decode()十、Python系统命令执行模块选型对比表选型说明表格聚焦各模块核心能力、适配场景精准区分优劣助力开发者根据实际需求快速选择合适的模块避免无效学习和使用风险标注「适用场景」为核心选型依据。模块/方法核心能力核心优势核心劣势适用场景选型优先级备注输出/安全性说明os.system()执行系统命令返回退出码语法简单一行代码即可执行无法捕获stdout/stderr无超时、无防注入功能单一临时调试、简单命令执行无需捕获输出最低仅临时使用输出直接打印到控制台无法在代码中复用无防注入设计不适合生产环境os.popen()执行命令可读取标准输出能简单捕获输出语法较简洁无法捕获stderr、无法获取返回码无超时易造成资源泄漏简单场景仅需读取输出无需判断执行状态低不推荐正式使用需手动读取输出流无法获取错误信息无防注入设计安全性一般commands模块执行命令可获取输出和返回码Python2Python2中可同时获取输出和返回码Python3已废弃无错误流分离无超时、无防注入无仅兼容Python2旧项目不推荐新增使用无已废弃仅Python2可用输出与错误流合并无法单独捕获stderrsubprocess模块执行命令、捕获stdout/stderr、获取返回码支持超时、异步、管道等高级操作功能全面安全可控防注入API统一支持跨平台可精细化控制进程语法较旧模块稍复杂需熟悉参数配置正式项目、运维脚本、服务端程序、复杂命令执行、需捕获输出/错误的场景最高强烈推荐可单独/合并捕获输出和错误返回结构化结果支持列表传参防注入适配生产环境选型建议临时调试、无需捕获输出可临时使用os.system()不推荐正式项目使用正式项目、运维脚本、需要捕获输出/错误、判断执行状态优先使用subprocess模块Python3项目严禁使用commands模块避免兼容性问题生产环境必须使用subprocess模块杜绝使用os.popen()降低安全风险和维护成本。十一、总结本文系统讲解了 Python3 subprocess 模块的基础用法、核心函数、高级特性、安全规范并提供 20 个覆盖高频场景的实战案例所有示例均以注释形式标注预期输出无需运行即可清晰理解执行结果。subprocess 是 Python 系统编程、自动化运维、脚本开发的核心模块掌握它可以轻松实现进程管理、命令调用、日志采集、服务监控等功能。建议结合案例动手练习逐步熟练使用后续可结合 psutil、logging 等模块构建完整的自动化工具。下一篇咱们学习 subprocess psutil 实现进程监控与系统巡检实战附录扩展学习资源官方文档https://docs.python.org/3/library/subprocess.htmlPython 标准库手册内置模块用法速查本专栏配套代码关注博主获取完整可运行工程文件联系博主专注 Python 自动化、后端开发、运维实战干货分享文章通俗易懂、案例可直接运行、零基础友好。 码字不易欢迎点赞 收藏 关注有问题可留言看到第一时间回复

更多文章