对Python subprocess.Popen子进程管道阻塞详解
问题产生描述
使用子进程处理一个大的日志文件,并对文件进行分析查询,需要等待子进程执行的输出结果,进行下一步处理。
出问题的代码
#启用子进程执行外部shell命令
def__subprocess(self,cmd):
try:
#执行外部shell命令,输出结果输出管道
p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
p.wait()
#从标准输出读出shell命令的输出结果
#rt=p.stdout.read().decode()
#以换行符拆分数据,并去掉换行符号存入列表
rt_list=rt.strip().split('\n')
exceptExceptionase:
if(DEBUG):
print(traceback.format_exc())
returnrt_list
问题分析
子进程产生一些数据,他们会被buffer起来,当buffer满了,会写到子进程的标准输出和标准错误输出,这些东西通过管道发送给父进程。当管道满了之后,子进程就停止写入,于是就卡住了,及时取走管道的输出就不会出现阻塞了
但是本人此处采取的是临时文件接收子进程输出,由于临时文件是建立在磁盘上的,没有size的限制,并且文件被close后,相应的磁盘上的空间也会被释放掉。
已改进的代码
importtempfile
#启用子进程执行外部shell命令
def__subprocess(self,cmd):
try:
#得到一个临时文件对象,调用close后,此文件从磁盘删除
out_temp=tempfile.TemporaryFile(mode='w+')
#获取临时文件的文件号
fileno=out_temp.fileno()
#执行外部shell命令,输出结果存入临时文件中
p=subprocess.Popen(cmd,shell=True,stdout=fileno,stderr=fileno)
p.wait()
#从临时文件读出shell命令的输出结果
out_temp.seek(0)
rt=out_temp.read()
#以换行符拆分数据,并去掉换行符号存入列表
rt_list=rt.strip().split('\n')
exceptExceptionase:
if(DEBUG):
print(traceback.format_exc())
finally:
ifout_temp:
out_temp.close()
returnrt_list
以上这篇对Pythonsubprocess.Popen子进程管道阻塞详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。