前言
关于subprocess.Popen阻塞问题之前就有遇到过,那时因为只执行一两个adb命令,所以在网上找了其他方法,功能勉强实现。就没有深入了解。
这次接到产品一个需求,要遍历150个ip,找出其中未禁ping的ip地址。adb命令操作多了后,subprocess.Popen阻塞问题彻底爆发了。最后不断试错,终于找到了communicate()。
改进前的代码
def oadb_cmd(cmd,index):
'''操作adb shell的方法'''
#得到一个临时文件,在close后删除,
# out_temp = tempfile.TemporaryFile()
out_temp = tempfile.SpooledTemporaryFile(max_size=10*1000)
fileno = out_temp.fileno()
res = subprocess.Popen(cmd,stdout=fileno,stderr=fileno,shell=True)
if res.poll() == None:
res.kill()
res.wait(timeout=30)
out_temp.seek(0) #指针移到开始处
rt = out_temp.readlines() #返回多行
str = ''
if rt != []:
str = rt[index].decode('gbk')
out_temp.flush()
out_temp.close() #关闭文件,文件就会自动删除
return str
改进后的代码
from subprocess import Popen,PIPE
def adb_cmd(cmd):
process = Popen(cmd,shell=True,stderr=PIPE,stdout=PIPE)
(stdout,stdrr) = process.communicate()
stdout = stdout.decode('gbk') #返回字段中存在中文,使用gbk
return stdout,stdrr
注意
不用导入下面模块。因为它们都是Popen对象的方法
from subprocess import communicate
from subprocess import wait
以上解决方法来自,感谢大佬!
https://www.pythonheidong.com/blog/article/65911/19d77d61e3f00bb95410/