您的位置:首页 > 编程语言 > Python开发

解决大量调用Python subprocess.Popen产生的一些bug

2017-12-21 09:40 537 查看
转自 :http://blog.csdn.net/pugongying1988/article/details/54616797

自从工作了就好久没发博客,还是出来冒个泡=。= 

前段时间写的一个项目需要用python的subprocess.Popen大量调用某shell命令,运行到一定量级之后就会产生内存溢出,造成大量线程阻塞,然后就会造成([Errno 24] Too many open files)这个异常。 

网上有人说是close_fds=True这个参数在python2.x默认没打开,这个参数可以关闭文件描述符,试了没有作用。 

后来在国外某个人的帖子找到了和我类似的问题,解决办法就是执行后把stdin,stdout,stderr3个流进行清空即可。 

结合网上的资料,写了一个可以自定义超时时间调用subprocess.Popen执行shell命令的函数(自定义超时为了避免某些shell卡死的情况),用这个函数去调用subprocess.Popen就不会产生上面这些问题了。
def timeout_command(command, timeout):
start = datetime.datetime.now()
process = subprocess.Popen(command, bufsize=10000, stdout=subprocess.PIPE, close_fds=True)
while process.poll() is None:
time.sleep(0.1)
now = datetime.datetime.now()
if (now - start).seconds> timeout:
try:
process.terminate()
except Exception,e:
return None
return None
out = process.communicate()[0]
if process.stdin:
process.stdin.close()
if process.stdout:
process.stdout.close()
if process.stderr:
process.stderr.close()
try:
process.kill()
except OSError:
pass
return out
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: