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 optional input argument should be a string to be sent to the child process, or None, 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 than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too.

Note The data read is buffered in memory, so do not use this method if the data size is large or unlimited.
我们可以在Popen()建立子进程的时候改变标准输入、标准输出和标准错误,并可以利用subprocess.PIPE将多个子进程的输入和输出连接在一起,构成管道(pipe):

import subprocess
child1 = subprocess.Popen(["ls","-l"], stdout=subprocess.PIPE)
child2 = subprocess.Popen(["wc"], stdin=child1.stdout,stdout=subprocess.PIPE)
out = child2.communicate()
print(out)
subprocess.PIPE实际上为文本流提供一个缓存区。child1的stdout将文本输出到缓存区,随后child2的stdin从该PIPE中将文本读取走。child2的输出文本也被存放在PIPE中,直到communicate()方法从PIPE中读取出PIPE中的文本。

要注意的是,communicate()是Popen对象的一个方法,该方法会阻塞父进程,直到子进程完成。

我们还可以利用communicate()方法来使用PIPE给子进程输入:

import subprocess
child = subprocess.Popen(["cat"], stdin=subprocess.PIPE)
child.communicate("vamei")
我们启动子进程之后,cat会等待输入,直到我们用communicate()输入"vamei"。

http://www.aikaiyuan.com/4705.html

https://buluo.qq.com/p/detail.html?bid=234299&pid=3596725-1483410241&from=share_copylink

最新文章

  1. vim如何配置go语言环境
  2. 21.Merge Two Sorted Lists(链表)
  3. git remove cache
  4. bzoj1355: [Baltic2009]Radio Transmission
  5. live555源码研究(四)------UserAuthenticationDatabase类
  6. Java 如何连接 SQL 2008 R2
  7. JDK源码阅读(一) ArrayList
  8. ASP.NET页面事件顺序
  9. C++基础学习笔记----第十四课(new和malloc的区别、单例模式等深入)
  10. Oulipo HDU 1686 KMP模板
  11. salesforce零基础学习(八十七)Apex 中Picklist类型通过Control 字段值获取Dependent List 值
  12. python学习之路网络编程篇(第五篇)
  13. C#导出文本内容到word文档源码
  14. Maven_2 本地资源库 中央存储库
  15. mysql练习题3
  16. MVC 在action方法中获取当前action的控制器名和action名
  17. nginx转发swoole以及nginx负载
  18. Dubbo学习笔记10:Dubbo服务消费方启动流程源码分析
  19. tomcat 用AXIS2发布WebService 网站的方法
  20. 关于keyCode, 键盘代码。 和零散的javascript知识。http://js2.coffee/(转化工具)

热门文章

  1. Failed to load C:\ProgramFilesTwo\Android\sdk\build-tools\27.0.3\lib\dx.jar
  2. psfaddtable - 添加一个Unicode字符表到控制台字体中
  3. standard_key.kmp
  4. mongodb 集合操作 (增删改查)
  5. AGC001[BCDE] 题解
  6. Gitbook环境搭建及制作——2019年10月24日
  7. MongoDB笔记【2】——基本概念和基本指令
  8. 【Dart学习】--之Runes与Symbols相关方法总结
  9. 【Linux】【Kibana】解决Kibana启动失败:Data too large问题
  10. bugku | login2(SKCTF) 200