在Python subprocess模块的学习过程中,你是否曾困惑于如何安全、高效地调用外部程序?本教程将带你从零开始,深入浅出地讲解 subprocess 模块的核心功能与最佳实践,即使是编程小白也能轻松上手!

subprocess 是 Python 标准库中的一个强大模块,用于创建新进程、连接到它们的输入/输出/错误管道,并获取返回码。它是替代旧版 os.system()、popen() 等函数的现代推荐方式。
使用 Python执行外部命令 的场景非常广泛,比如:
ls、dir、ping)自 Python 3.5 起,官方推荐使用 subprocess.run() 来执行命令。它简单、安全且功能全面。
import subprocess# 执行一个简单的命令并等待完成result = subprocess.run(['ls', '-l'], capture_output=True, text=True)print("返回码:", result.returncode)print("标准输出:\n", result.stdout)print("标准错误:\n", result.stderr)参数说明:
['ls', '-l']:命令以列表形式传入,避免 shell 注入风险capture_output=True:捕获标准输出和标准错误text=True:以字符串形式返回输出(否则是 bytes)有时你需要使用 shell 功能(如管道、重定向),这时可以设置 shell=True,但要注意安全风险!
# 示例:使用 shell 管道result = subprocess.run( "echo 'Hello World' | grep Hello", shell=True, capture_output=True, text=True)print(result.stdout) # 输出: Hello World ⚠️ 警告:当使用用户输入构造命令时,永远不要 使用 shell=True,否则可能导致命令注入漏洞!当你需要更精细的控制(如实时读取输出、与进程交互),可以使用 subprocess.Popen。
import subprocess# 启动一个长期运行的进程proc = subprocess.Popen( ['ping', 'baidu.com'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)# 实时读取输出for line in proc.stdout: print(line.strip()) if "64 bytes" in line: break # 收到一次响应就退出proc.terminate() # 终止进程良好的代码应处理命令失败的情况:
try: result = subprocess.run( ['nonexistent-command'], check=True, # 如果返回码非0,抛出 CalledProcessError capture_output=True, text=True )except subprocess.CalledProcessError as e: print(f"命令执行失败!返回码: {e.returncode}") print(f"错误信息: {e.stderr}")通过本篇 subprocess教程,你应该已经掌握了 Python subprocess模块 的核心用法。记住以下几点:
subprocess.run()shell=TruePopen希望这篇 subprocess使用详解 能帮助你在项目中安全高效地调用外部命令!
本文由主机测评网于2025-12-16发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025128515.html