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. Prometheus + Grafana

    Prometheus ubuntu安装prometheus非常简单: apt update apt install prometheus systemctl enable prometheus sys ...

  2. HTML基础 块级元素和内联元素

    大多数 HTML 元素被定义为块级元素或内联元素. 块级元素包括:body  from  select  textarea  h1-h6 html table  button  hr  p  ol   ...

  3. Codeforces 963B Destruction of a Tree 思维+dfs

    题目大意: 给出一棵树,每次只能摧毁有偶数个度的节点,摧毁该节点后所有该节点连着的边都摧毁,判断一棵树能否被摧毁,若能,按顺序输出摧毁的点,如果有多种顺序,输出一种即可 基本思路: 1)我一开始自然而 ...

  4. python的转义字符,以及字符串输出转义字符

    Python的转义字符及其含义     符    号     说     明       \'   单引号       \"   双引号       \a   发出系统响铃声       \ ...

  5. SQL必知必会学习笔记

    2.5  select SELECT       要返回的列或表达式     是FROM          从中检索数据的表        仅在从表选择数据时使用WHERE        行级过滤   ...

  6. boost phoenix

    In functional programming, functions are objects and can be processed like objects. With Boost.Phoen ...

  7. Java反射及注解学习- 反射的使用 - JDK动态代理

    代理模式基本概念:1.代理模式的作用:为其他对象提供一种以控制对方的访问在某种情况下,一个客户不想或者不能直接引用另一个对象,代理可以在客户端和目标对象之间起到中介的作用代理的角色:(1)抽象角色:声 ...

  8. Java Web学习总结(7)JSP(一)

    一,JSP基础语法 1,JSP模板元素 JSP页面中的HTML内容称之为JSP模版元素. JSP模版元素定义了网页的基本骨架,即定义了页面的结构和外观. 2,JSP脚本片段 JSP脚本片断(scrip ...

  9. BDE(一款数据库引擎,通过它可以连接不同数据库)

    BDE(Borland Database Engine)是Inprise公司的数据库引擎,它结合了SQL Links允许程序员通过它能够连接到各种不同的数据库.BDE是BORLAND 数据库引擎的缩写 ...

  10. MySQL中truncate误操作后的数据恢复案例

    MySQL中truncate误操作后的数据恢复案例 这篇文章主要介绍了MySQL中truncate误操作后的数据恢复案例,主要是要从日志中定位到truncate操作的地方然后备份之前丢失的数据,需要的 ...