上一篇
Python subprocess模块使用教程 - 详细指南与示例
- Python
- 2025-07-20
- 691
Python subprocess模块使用教程
学习如何使用Python的subprocess模块执行外部命令、管理子进程、处理输入输出流及错误处理
subprocess模块简介
Python的subprocess
模块允许你生成新的进程,连接到它们的输入/输出/错误管道,并获取它们的返回码。
它是用来替代以下旧模块的更好选择:
os.system
os.spawn*
os.popen*
popen2.*
commands.*
基础用法 - 使用subprocess.run()
subprocess.run()
是Python 3.5+引入的高级函数,用于执行命令并等待其完成。
基本命令执行
import subprocess # 执行简单命令 result = subprocess.run(['ls', '-l'], capture_output=True, text=True) print("返回码:", result.returncode) print("标准输出:", result.stdout) print("标准错误:", result.stderr)
处理错误
import subprocess try: # 执行一个可能失败的命令 result = subprocess.run(['grep', 'python', 'nonexistent.txt'], capture_output=True, text=True, check=True) except subprocess.CalledProcessError as e: print(f"命令执行失败! 返回码: {e.returncode}") print(f"错误输出: {e.stderr}")
高级用法 - 使用Popen类
当需要更细粒度的控制时,可以使用subprocess.Popen
类。
实时读取输出
import subprocess # 执行命令并实时读取输出 with subprocess.Popen(['ping', '-c', '4', 'google.com'], stdout=subprocess.PIPE, text=True) as proc: # 实时读取输出 for line in proc.stdout: print(line, end='') # 等待进程结束 proc.wait() print(f"\\n进程结束,返回码: {proc.returncode}")
管道连接多个命令
import subprocess # 执行多个命令:ps aux | grep python ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE) grep = subprocess.Popen(['grep', 'python'], stdin=ps.stdout, stdout=subprocess.PIPE, text=True) # 获取最终输出 output, _ = grep.communicate() print("包含python的进程:") print(output)
输入输出重定向
向子进程提供输入
import subprocess # 启动一个需要输入的程序 with subprocess.Popen(['grep', 'python'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) as proc: # 提供输入内容 input_text = "hello\\nworld\\npython\\nprogramming" output, _ = proc.communicate(input_text) print("过滤后的输出:") print(output)
重定向到文件
import subprocess # 将输出重定向到文件 with open('output.txt', 'w') as f: result = subprocess.run(['ls', '-l', '/usr'], stdout=f, text=True) print("输出已写入output.txt文件")
安全提示
避免使用shell=True: 除非必要,否则应避免使用shell=True
参数,因为它可能带来安全风险(如shell注入攻击)。
不安全的写法:
user_input = input("请输入文件名: ") subprocess.run(f"cat {user_input}", shell=True) # 危险!
安全的写法:
user_input = input("请输入文件名: ") subprocess.run(["cat", user_input]) # 安全
总结
subprocess模块提供了强大而灵活的方法来创建和管理子进程:
- 使用
subprocess.run()
执行简单命令 - 使用
subprocess.Popen
进行高级控制 - 通过管道连接多个命令
- 重定向输入/输出到文件或其他流
- 处理错误和返回码
掌握这些技术将使你能够将Python脚本与系统命令和其他程序无缝集成。
本文由QianShou于2025-07-20发表在吾爱品聚,如有疑问,请联系我们。
本文链接:http://pjw.521pj.cn/20256080.html
发表评论