脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - 对Python subprocess.Popen子进程管道阻塞详解

对Python subprocess.Popen子进程管道阻塞详解

2021-04-14 00:09独一无二的小个性 Python

今天小编就为大家分享一篇对Python subprocess.Popen子进程管道阻塞详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

问题产生描述

使用子进程处理一个大的日志文件,并对文件进行分析查询,需要等待子进程执行的输出结果,进行下一步处理。

出问题的代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 启用子进程执行外部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')
 
 except Exception as e:
 if(DEBUG):
  print(traceback.format_exc())
 
 return rt_list

问题分析

子进程产生一些数据,他们会被buffer起来,当buffer满了,会写到子进程的标准输出和标准错误输出,这些东西通过管道发送给父进程。当管道满了之后,子进程就停止写入,于是就卡住了,及时取走管道的输出就不会出现阻塞了

但是本人此处采取的是临时文件接收子进程输出,由于临时文件是建立在磁盘上的,没有size的限制,并且文件被close后,相应的磁盘上的空间也会被释放掉。

已改进的代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import tempfile
# 启用子进程执行外部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')
 
 except Exception as e:
 if(DEBUG):
  print(traceback.format_exc())
 
 finally:
 if out_temp:
  out_temp.close()
 
 return rt_list

以上这篇对Python subprocess.Popen子进程管道阻塞详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/u010649766/article/details/75573887

延伸 · 阅读

精彩推荐