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. centos7解决ssh登录速度慢的问题

    先备份/etc/ssh/sshd_config,备份命令为 cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak 1.su                  ...

  2. poj 1845 Sumdiv (等比求和+逆元)

    题目链接:http://poj.org/problem?id=1845 题目大意:给出两个自然数a,b,求a^b的所有自然数因子的和模上9901 (0 <= a,b <= 50000000 ...

  3. C++链接器

    链接器把多个二进制的目标文件(object file)链接成一个单独的可执行文件 在链接过程中,它必须把符号(变量名.函数名等一些列标识符)用对应的数据的内存地址(变量地址.函数地址等)替代,以完成程 ...

  4. Linux 给用户 赋某个文件夹操作的权限

    https://my.oschina.net/cqyj/blog/1796047 在root用户登录的情况,赋予opt目录给liuhai这个用户权限 示例代码: # 将目录/opt 及其下面的所有文件 ...

  5. Properties工具类学习

    Properties类学习 1.定义 Properties,java.utils包下的一个工具类,主要用于读取Java的配置文件.各种语言都有自己所支持的配置文件,配置文件中很多变量是经常变动的. 这 ...

  6. JS中关于构造函数、原型链、prototype、constructor、instanceof、__proto__属性

    在Javascript不存在类(Class)的概念,javascript中不是基于类的,而是通过构造函数(constructor)和原型链(prototype chains)实现的.但是在ES6中引入 ...

  7. 2019 牛客暑期多校 第三场 F Planting Trees (单调队列+尺取)

    题目:https://ac.nowcoder.com/acm/contest/883/F 题意:求一个矩阵最大面积,这个矩阵的要求是矩阵内最小值与最大值差值<=m 思路:首先我们仔细观察范围,我 ...

  8. [CSP-S模拟测试]:God Knows(线段树维护单调栈)

    题目描述 小$w$来到天堂的门口,对着天堂的大门发呆.大门上有一个二分图,左边第$i$个点连到右边第$p_i$个点.(保证$p_i$是一个排列).小$w$每次可以找左边某个对应连线尚未被移除的点$i$ ...

  9. 二次封装dojo slider

    上次的二次封装timeslider,挺有意思,又来封装一个dojo的,样式还是用arcgis的.实现更多功能,包括HorizontalSlider和VerticalSlider, 刻度的显示隐藏,标签 ...

  10. cnn模型

    https://blog.csdn.net/qq_26591517/article/details/79805884