刚开始我是使用的wait(),但是当adb命令返回太多时,程序就会卡死,查询得知原因后,才使用了communicate(),communicate()返回一个元组:(stdoutdata, stderrdata)

原因如下
转自:http://blog.csdn.net/carolzhang8406/article/details/22286913
 

之所以会纠结到这个问题上是因为发现在调用Popen的wait方法之后程序一直没有返回。google发现wait是有可能产生死锁的。为了把这个问题彻底弄清楚,搜索一些资料过来看看:

看到别人的例子:

今天遇到的一个问题。简单说就是,使用 subprocess 模块的 Popen 调用外部程序,如果 stdout 或 stderr 参数是
pipe,并且程序输出超过操作系统的 pipe
size时,如果使用 Popen.wait() 方式等待程序结束获取返回值,会导致死锁,程序卡在 wait() 调用上。

ulimit -a 看到的 pipe size 是
4KB,那只是每页的大小,查询得知 linux 默认的 pipe
size 是 64KB

看例子:

  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. # yc@2013/04/28
  4. import subprocess
  5. def test(size):
  6. print 'start'
  7. cmd = 'dd if=/dev/urandom bs=1 count=%d 2>/dev/null' % size
  8. p = subprocess.Popen(args=cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True)
  9. #p.communicate()
  10. p.wait()
  11. print 'end'
  12. # 64KB
  13. test(64 * 1024)
  14. # 64KB + 1B
  15. test(64 * 1024 + 1)
  16.  

首先测试输出为 64KB 大小的情况。使用 dd 产生了正好 64KB 的标准输出,由 subprocess.Popen 调用,然后使用 wait() 等待 dd 调用结束。可以看到正确的 start 和 end 输出;然后测试比 64KB 多的情况,这种情况下只输出了 start,也就是说程序执行卡在了 p.wait() 上,程序死锁。具体输出如下:

  1. start
  2. end
  3. start
  4.  

那死锁问题如何避免呢?官方文档里推荐使用 Popen.communicate()。这个方法会把输出放在内存,而不是管道里,所以这时候上限就和内存大小有关了,一般不会有问题。而且如果要获得程序返回值,可以在调用 Popen.communicate() 之后取 Popen.returncode 的值。

结论:如果使用 subprocess.Popen,就不使用 Popen.wait(),而使用 Popen.communicate() 来等待外部程序执行结束。

Popen.wait()

Wait for child process to terminate.  Set and returnreturncode attribute.

Warning

This will deadlock when using stdout=PIPE and/orstderr=PIPE and the child process generates enough output to a pipe such that it blocks waiting for the OS pipe buffer to accept more data.  Use communicate() to avoid that.

Popen.communicate(input=None)

Interact with process: Send data to stdin.  Read data from stdout and stderr, until end-of-file is reached.  Wait for process to terminate. The optionalinput argument should be a string to be sent to the child process, orNone, if no data should be sent to the child.

communicate() returns a tuple (stdoutdata, stderrdata).

Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE.  Similarly, to get anything other thanNone in the result tuple, you need to give stdout=PIPE and/orstderr=PIPE too.

Note

The data read is buffered in memory, so do not use this method if the data size is large or unlimited.

subprocess 的两种方法:

1)如果想调用之后直接阻塞到子程序调用结束:

Depending on how you want to work your script you have two options. If you want the commands to block and not do anything while it is executing, you can just use subprocess.call.

  1. #start and block until done
  2. subprocess.call([data["om_points"],">", diz['d']+"/points.xml"])
  1.  
  1. 2)非阻塞的时候方式:

If you want to do things while it is executing or feed things into stdin, you can use communicate after the popen call.

  1. #start and process things, then wait
  2. p = subprocess.Popen(([data["om_points"],">", diz['d']+"/points.xml"])print"Happens while running"
  3. p.communicate()#now wait

As stated in the documentation, wait can deadlock, so communicate is advisable.

Python subprocess.Popen中communicate()和wait()区别的更多相关文章

  1. python subprocess popen 静默模式(不弹出console控制台)

    python subprocess popen 静默模式(不弹出console控制台) import subprocess,sys IS_WIN32 = 'win32' in str(sys.plat ...

  2. Python subprocess.Popen communicate() 和wait()使用上的区别

    之所以会纠结到这个问题上是因为发现在调用Popen的wait方法之后程序一直没有返回.google发现wait是有可能产生死锁的.为了把这个问题彻底弄清楚,搜索一些资料过来看看: 原文链接:http: ...

  3. Python: subprocess.Popen()不支持unicode问题解决

    起源: 所下载视频,有音视频分离者,需要合并起来,采用python之subprocess.Popen()调用ffmpeg实现.python版本为2.7.13,而音视频文件路径,有unicode字符者, ...

  4. Python Subprocess Popen 管道阻塞问题分析解决

    http://ju.outofmemory.cn/entry/279026 场景:1>不断播放mp3文件: 2>使用订阅发布模式保持tcp长连接,从服务器接收信息 造成程序hang死,但是 ...

  5. Python subprocess Popen

    目的:顺序执行进程  在Bash里面类似  a.sh && b.sh && c.sh 先来说下Popen这个函数 class subprocess.Popen(args ...

  6. python subprocess.Popen 非阻塞

    1.非阻塞设置subprocess.Popen(args, stdout=subprocess.PIPE,stderr=subprocess.PIPE) def non_block_read(outp ...

  7. python subprocess.Popen 控制台输出 实时监控百度网ping值

    import subprocess file_out = subprocess.Popen('ping www.baidu.com', shell=True, stdout=subprocess.PI ...

  8. 【python】json中load和loads区别

    相同点 dump 和 dumps 都实现了序列化 load 和 loads 都实现反序列化 变量从内存中变成可存储或传输的过程称之为序列化序列化是将对象状态转化为可保存或可传输格式的过程. 变量内容从 ...

  9. Python面试题之Python和Java中Super方法的区别

    python 的 super 是一个函数,需要两个参数,第一个参数是类,第二个参数是实例,返回值是一个类对象. 其意义是:站在参数2这个实例的角度看去, 参数1这个类的‘父亲’是谁,把‘父亲’返回. ...

随机推荐

  1. hihoCoder hiho一下 第二周 #1014 : Trie树(Trie树基本应用)

    思路: 完全看题目中的介绍就行了.还有里面的input写道:不保证是英文单词,也有可能是火星文单词哦.比赛结束后的提交是不用考虑26个字母之外的,都会AC,如果考虑128种可能的话,爆了内存.步骤就是 ...

  2. 慎用python的pop和remove方法

    申明:转载请注明出处!!! Python关于删除list中的某个元素,一般有两种方法,pop()和remove(). 如果删除单个元素,使用基本没有什么问题,具体如下. 1.pop()方法,传递的是待 ...

  3. SQLSERVER 创建ODBC 报错的解决办法 SQLState:'01000'的解决方案

    错误详情如下: SQLState:'01000' SQL Server 错误:14 [Microsoft][ODBC SQL Server Driver][DBNETLIB] ConnectionOp ...

  4. [转载]AngularJS快速开始

    AngularJS快速开始 Hello World! 开始学习AngularJS的一个好方法是创建经典应用程序“Hello World!”: 使用您喜爱的文本编辑器,创建一个HTML文件,例如:hel ...

  5. react的redux中间件

    redux 的中间件(对dispatch功能的拦截和增强,一般不用自己写,有插件) dispath是一个方法,可以自行中间拦截更改: store.dispatch = function(action) ...

  6. .NET下寄宿于控制台的HTTPS监听

    附上原文链接:https://blogs.msdn.microsoft.com/jpsanders/2009/09/29/how-to-walkthrough-using-httplistener-o ...

  7. PHP 工厂模式介绍

    工厂模式,顾名思义,如同工厂一样,你把原材料放入工厂中,出来的是成品,而你并不需要知道工厂里做了什么.代码中也类似,把主要参数放入一个工厂里,返回的是处理好的数据,我们并不需要工厂里做了什么,只需要知 ...

  8. LeetCode946-验证栈序列

    问题:验证栈序列 给定 pushed 和 popped 两个序列,只有当它们可能是在最初空栈上进行的推入 push 和弹出 pop 操作序列的结果时,返回 true:否则,返回 false . 示例 ...

  9. python笔记-list列表的方法

    #!usr/bin/python # -*- coding: utf-8 -*- # 存储5个人的年龄,求他们的平均年龄 age1 = 18 age2 = 15 age3 = 38 age4 = 20 ...

  10. spring MVC体系结构和请求控制器

    MVC处理过程 spring MVC架构模式都进行了分层设计如下 数据访问接口:DAO层 处理业务逻辑层:service层 数据实体:POJO 负责前端请求的接受并处理:servlet 负责前端页面展 ...