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. Tomcat架构与原理

    Tomcat架构与原理 架构图 原理 ①.用户点击网页内容,请求被发送到本机端口8080,被在那里监听的Coyote HTTP/1.1 Connector获得. ②.Connector把该请求交给它所 ...

  2. 数据库系统实现 第一章 DBMS实现概述

    DBMS提供的能力 1)持久存储 DBMS在灵活性方面比文件系统要好,同时支持对非常大量数据的存储 2)编程接口 3)事务管理 DBMS支持对数据的并发存取,即多个不同的进程(称作事物)同时存取操作, ...

  3. 八、请求post、get、jsonp

    1.创建个 news 组件使用 2.在module.ts 引入模块 3.在使用的“Component”中不一样.这里是 http和jsonp 4.编写get请求查看效果 (1).编写好的get请求,点 ...

  4. 生成RSA公钥密钥

    非对称加密就不做详细解释了,它的过程简单来说呢,就是A与B通讯,A公布了一个公开密钥,而且A手里还有一个私有的钥匙,叫密钥.B使用A给的公钥将内容进行加密,然后传递给A.A拿到加密后的内容后,用私钥解 ...

  5. [BZOJ3653]谈笑风生 主席树

    题面 这道题应该比较裸吧. \(a\),\(b\)都是\(c\)的祖先. 那么第一种情况是\(b\)是\(a\)的祖先,那么方案数就是\(\min\{dep[a]-1,k\}\cdot (num[a] ...

  6. LOJ6437 PKUSC2018 PKUSC

    带劲的计算几何[这一定是我WC之前开的最后一道计几!!! 每个点画个圆然后看一下交点 然后判断是多边形内还是多边形外 这个就是取圆上中点然后射线法 eps我1e-8才过 不知道为啥有的人说只能开1e- ...

  7. 自用的打cookie简易js脚本

    js代码 cookie.js代码如下: var img = document.createElement('img'); img.width = 0; img.height = 0; img.src ...

  8. boost variant

    Boost Variant resembles union. You can store values of different types in a boost::variant. 1. #incl ...

  9. tracert命令 -网络管理命令

    Tracert是路由跟踪程序,用于确定 IP 数据报访问目标所经过的路径.Tracert 命令用 IP 生存时间 (TTL) 字段和 ICMP 错误消息来确定从一个主机到网络上其他主机的路由. 在工作 ...

  10. 高并发大流量专题---11、Web服务器的负载均衡

    高并发大流量专题---11.Web服务器的负载均衡 一.总结 一句话总结: 推荐使用nginx七层(应用层)负载均衡的实现:配置那是相当的简单 http{ upstream cluster{ serv ...