网问答>>Python subprocess模块学习总结
问题
已解决

Python subprocess模块学习总结

时间:2026-04-11 03:05:24
Python subprocess模块学习总结
最佳回答
Python subprocess模块是用于创建和管理子进程的核心模块,自Python 2.4引入后逐步替代了os.system、os.popen等旧方法。它支持调用外部命令、控制子进程的输入/输出/错误流,并通过管道实现进程间通信。一、常用封装函数subprocess模块提供了三个高频使用的封装函数,均基于Popen类实现,简化了子进程的调用与结果处理:subprocess.call()父进程阻塞等待子进程完成,返回退出状态码(returncode,对应Linux的exit code)。示例:import subprocessretcode = subprocess.call(["ls", "-l"]) # 使用列表传递命令和参数print(retcode) # 输出0(成功)通过shell=True可启用Shell解释命令字符串(但需注意安全风险):retcode = subprocess.call("ls -l", shell=True) # 直接传递字符串subprocess.check_call()行为与call()类似,但若子进程返回非零状态码(失败),会抛出subprocess.CalledProcessError异常。示例:try: subprocess.check_call(["false"]) # 模拟失败命令except subprocess.CalledProcessError as e: print(f"Error: {e.returncode}") # 输出错误码subprocess.check_output()返回子进程的标准输出(stdout),若返回非零状态码则抛出异常(含output属性)。示例:try: output = subprocess.check_output(["echo", "Hello"]) print(output.decode()) # 输出"Hellon"except subprocess.CalledProcessError as e: print(f"Error: {e.output.decode()}")二、核心类Popen封装函数无法满足复杂需求时,需直接使用Popen类,它提供了更精细的子进程控制能力:基本用法创建子进程后,父进程默认不阻塞,需手动调用wait()等待结束:child = subprocess.Popen(["ping", "-c", "4", "example.com"])print("Parent process continues") # 立即执行child.wait() # 阻塞直到子进程结束print("Child process finished")进程控制方法poll():检查子进程是否结束,返回状态码或None(未结束)。kill()/terminate():强制终止子进程(kill发送SIGKILL,terminate发送SIGTERM)。send_signal(signal):发送指定信号(如signal.SIGINT)。示例:child = subprocess.Popen(["sleep", "10"])if child.poll() is None: # 子进程未结束 child.terminate() # 尝试优雅终止进程ID访问子进程的PID通过child.pid属性获取:print(f"Child PID: {child.pid}")三、子进程文本流控制通过stdin、stdout、stderr参数可重定向子进程的输入/输出流,结合subprocess.PIPE实现管道通信:捕获输出设置stdout=subprocess.PIPE后,通过stdout.read()或communicate()获取输出:child = subprocess.Popen(["ls", "-l"], stdout=subprocess.PIPE)output, _ = child.communicate() # communicate()同时处理stdout和stderrprint(output.decode())管道连接将多个子进程的流串联,构建复杂管道:# 示例:统计/etc/passwd中以"root"开头的行数cat = subprocess.Popen(["cat", "/etc/passwd"], stdout=subprocess.PIPE)grep = subprocess.Popen(["grep", "^root"], stdin=cat.stdout, stdout=subprocess.PIPE)wc = subprocess.Popen(["wc", "
时间:2026-04-11 03:05:28
本类最有帮助
Copyright © 2008-2013 www.wangwenda.com All rights reserved.冀ICP备12000710号-1
投诉邮箱: