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
随机推荐
- rtp/rtcp
rtp/rtcp stack custom rtp ORTP UCL Common RTP library Bell Labs RTP Library jrtplib 1.custom rtp sen ...
- linux性能分析工具Vmstat
- day03 for循环、字符串方法、类型转换
01 上周内容回顾 while 条件: 循环体 例: while True: print(111) print(222) print(333) 结束循环的两种方式: 1,改变条件. 2,break. ...
- MySQL--11 备份的原因
目录 一.备份的原因 二.备份的类型 三.备份的方式 四.备份策略 五.备份工具 六.企业故障恢复案例 1.模拟环境 2.模拟恢复数据过程: 一.备份的原因 运维工作的核心简单概括就两件事: 1)第一 ...
- Mysql --09 Innodb核心特性——事务
目录 Innodb核心特性--事务 1.什么是事务 2.事务的通俗理解 3.事务ACID特性 4.事务流程举例 5.事务的控制语句 6.事务隐式提交情况 7.事务日志redo基本功能 8.redo数据 ...
- 后缀自动机(SAM) 学习笔记
最近学了SAM已经SAM的比较简单的应用,SAM确实不好理解呀,记录一下. 这里提一下后缀自动机比较重要的性质: 1,SAM的点数和边数都是O(n)级别的,但是空间开两倍. 2,SAM每个结点代表一个 ...
- OtterCTF - Reverse - Msg Me This
原文地址:Msg Me This 题目 Category: Reverse Engineering Points: 500 Solves: 15 Description: Rick created a ...
- java pravite关键字的使用
package java04; /* * 问题描述:定义Person的年龄时,无法阻止不合理的数值设置进来 * 解决方案:用private关键字将需要保护的成员变量进行修饰 * * 一旦使用了priv ...
- CF 36E Two Paths
传送门 真实的自闭= =+ 考试的时候老师明明说了可以路径为空T^T 然后光荣的挂掉了 20分的链[明明是最送分的] 上来就看出来欧拉回路了嘛 然后思考了一下大概奇点配个对 删一条简单路径剩下的跑欧拉 ...
- CF840E In a Trap
题意:给你一棵节点带权树.q个询问,每次询问u到v的路径上max(a[i]^dis(i,v))? 保证u是v的祖先,i是u->v路径上的点.n,ai<=5e4. 标程: #include& ...