常用模块——subprocess模块

subprocess模块

 subprocess主要用于执行系统指令(启动子进程)与os.system 的不同在于

#subprocess可以与这个子进程进行数据交换。

import subprocess
#从管道中读取数据   管道就是 两个进程通讯的媒介
cmd = r'dir F:\Python_exe'
res = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE)#cmd 命令语句 shell选项 stdout输出正确管道
print(res.stdout.read().decode('GBK'))

 

dir = r'dir F:\Python_exe\day21'
finder = r'findstr py'
res = subprocess.Popen(dir,shell=True,stdout=subprocess.PIPE,)
#                                               正确输出端口          输入端口               错误输出端口
res1 = subprocess.Popen(finder,shell=True,stdout=subprocess.PIPE,stdin=res.stdout,stderr=subprocess.PIPE)
# 输出的端口 stdout stderr 都用subprocess.PIPE stdin接受其他subprocess对象的输出
print(res.stdout.read().decode('GBK'))
print(res1.stdout.read().decode('GBK'))
print(res1.stderr.read().decode('GBK'),2222)#没有错误信息不显示

 

posted @ 2018-10-19 20:19  msjaxuexi  阅读(189)  评论(0编辑  收藏  举报