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
随机推荐
- Linux学习笔记2-CentOS7安装tomcat8
1.下载tomcat:apache-tomcat-8.5.16.tar.gz 下载地址:http://mirrors.tuna.tsinghua.edu.cn/apache/tomcat/tomcat ...
- vue,一路走来(5)--微信登录
微信登录 今天又是周末了,想着博客还没记录完成.是的,下面记录一下微信登录遇到的问题. 在我的项目中,个人中心是需要完成授权登录才可以访问的,首先在定义路由的时候就需要多添加一个自定义字段requir ...
- kotlin中实现匿名内部类
1.常规的方式实现匿名内部类 valueAnimator.addUpdateListener(object :AnimatorUpdateListener { override fun onAnima ...
- windows H2database 安装
转载百度经验 H2是一个开源的.纯java实现的关系数据库,小巧并且使用方便,十分适合作为嵌入式数据库使用 首先打开浏览器进入H2官网http://www.h2database.com/html/ma ...
- wxpython 文本框TextCtrl
path_text = wx.TextCtrl(frame, pos=(5, 5), size=(350, 24))最常用的两个函数:path = path_text.GetValue() conte ...
- 终端、mac等小技巧——2019年10月18日
1.新建finder窗口 cmd+N 2.查看文件夹结构 brew install tree tree命令行参数(只实用与安装了tree命令行工具): -a 显示所有文件和目录. -A 使用ASNI绘 ...
- JavaWeb(五):MVC案例
MVC是Model-View-Controller的简称,即模型-视图-控制器.MVC是一种设计模式,它把应用程序分成三个核心模块:模型.视图.控制器,它们各自处理自己的任务.模型是应用程序的主体部分 ...
- 【leetcode】714. Best Time to Buy and Sell Stock with Transaction Fee
题目如下: Your are given an array of integers prices, for which the i-th element is the price of a given ...
- 在使用KVO遇到的一个问题
在项目开发中定义了一个单例对象RHUserData的对象,RHOLUserInfo类是单例对象的一个property属性,RHOLUserInfo里面有个userId的属性,在其他类里面进行设置KVO ...
- Python游戏
要想实现键盘控制作用,就需要给游戏键盘监听事件利用pygame模块的key.get_pressed()方法,来检测按键是否按下 key_press =pygame.key.get_pressed() ...