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. shell函数与位置参数举例

  2. OutOfMemoryError系列(2): GC overhead limit exceeded

    原因分析 JVM抛出 java.lang.OutOfMemoryError: GC overhead limit exceeded 错误就是发出了这样的信号: 执行垃圾收集的时间比例太大, 有效的运算 ...

  3. 莫比乌斯反演/线性筛/积性函数/杜教筛/min25筛 学习笔记

    最近重新系统地学了下这几个知识点,以前没发现他们的联系,这次总结一下. 莫比乌斯反演入门:https://blog.csdn.net/litble/article/details/72804050 线 ...

  4. procixx和最近调试的坑

    流程: 1.procixx/vivado 配置soc硬件信息,导出FSBL.out: 2.配置uboot dts,生成u-boot (需要打开的硬件 配置为status = "okay&qu ...

  5. Swagger添加文件上传测试

    先上对比图 图一无法选择文件,图二可以选择文件 图一 图二 添加过滤器 public class SwaggerFileUploadFilter : IOperationFilter { /// &l ...

  6. html5 像素模拟渐变

    代码实例: <!DOCTYPE html> <html> <head> <style> canvas{ background:#eee; } </ ...

  7. Delphi Win API 函数 MulDiv

    Delphi Win API 函数 MulDiv 原型:function MulDiv(nNumber, nNumerator, nDenominator: Integer): Integer; st ...

  8. Centos7安装Nginx1.14.0

    一.官网下载 http://nginx.org/en/download.html 版本说明: Nginx官网提供了三个类型的版本 Mainline version:Mainline 是 Nginx 目 ...

  9. 深度学习中的batch、epoch、iteration的含义

    深度学习的优化算法,说白了就是梯度下降.每次的参数更新有两种方式. 第一种,遍历全部数据集算一次损失函数,然后算函数对各个参数的梯度,更新梯度.这种方法每更新一次参数都要把数据集里的所有样本都看一遍, ...

  10. StrictMode 严格模式

    StrictMode: 帮助程序员避免在主线程上执行耗时操作: 启动级别: 1. 启动线程级别:   setThreadPolicy() 2. 启动应用级别 :  setVmPolicy() —— 对 ...