sub
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
随机推荐
- python常用函数 R
replace(str, str) 字符串替换. 例子: rjust(int) 格式化字符串,右对齐,支持传入填充值. 例子: rstrip(str) 删去右边的参数,支持传入参数. 例子: roun ...
- 解决Minikube start卡住的方法
安装与问题 在mac上安装minikube对k8s进行学习,根据官方Quick Start brew cask install minikube 就可以完成minikube的安装 在安装前需要安装vi ...
- 3.VUE前端框架学习记录三:Vue组件化编码1
VUE前端框架学习记录三:Vue组件化编码1文字信息没办法描述清楚,主要看编码Demo里面,有附带完整的代码下载地址,有需要的同学到脑图里面自取.脑图地址http://naotu.baidu.com/ ...
- apache You don't have permission to access / on this server.无权访问
环境:ubuntu16.4 apache2 原因:修改了apache web项目路径 解决: 1. 修改 /etc/apache2/sites-available/000-default.conf 文 ...
- kill命令的几种信号
1 HUP: hangup 2 INIT: 相当于 Ctrl + c 9 KILL 15 TERM: Terminate (kill 的默认信号) 18 CONT: Continue (从STOP信号 ...
- json序列化反序列
json只能处理简单的数据类型:字典 列表等... 文件只能存字符串和二进制 序列化:把内存的对象变为字符串 反序列化:将字符串变回为内存对象
- C/C++ C++ 11 std::function和std::bind用法
std::bind() std::bind 主要用于绑定生成目标函数,一般用于生成的回调函数,cocos的回退函数都是通过std::bind和std::function实现的.两个点要明白: 1.绑定 ...
- 【LeetCode 84】柱状图中最大的矩形
题目链接 [题解] 维护一个单调递增的栈. 会发现栈内的第i个元素的前面一个(i-1)元素在原始的序列中的数字 都是要高于第i个元素的.(或者没有元素) 那么第i个元素往左最多可以扩展到第i-1个元素 ...
- Android中插件开发篇总结和概述
刚刚终于写完了插件开发的最后一篇文章,下面就来总结一下,关于Android中插件篇从去年的11月份就开始规划了,主要从三个方面去解读Android中插件开发原理.说白了,插件开发的原理就是:动态加载技 ...
- paper 167:GPU的使用Theano之tutorial
Theano之使用GPU 英文版本:http://deeplearning.net/software/theano/tutorial/using_gpu.html using the ...