PythonStudy——subprocess 模块

subprocess 称之为子进程,进程是一个正在运行的程序

为什么要使用子进程,因为之前的os.system()函数无法获取命令的执行结果,另一个问题是当我们启动了某一其他进程时无法与这个子进程进行通讯,

当要在python程序中执行系统指令时 就应该使用subprocess 自动化运维经常会使用

#测试
res = os.system("python")
print(res)
# res结果为执行状态
# 程序无法正常结束

 

 

subprocess的使用

import subprocess


p = subprocess.Popen("dir",shell=True,stdout=subprocess.PIPE)
print(p.stdout.read().decode("GBK"))

#shell=True 告诉系统这是一个系统指令 而不是某个文件名 #此时效果与sys.system()没有任何区别,都是将结果输出到控制台 # 那如何与这个进程交互数据呢,这需要用到三个参数 1.stdin 表示输入交给子进程的数据 2.stdout 表示子进程返回的数据 3.stderr 表示子进程发送的错误信息 #这三个参数,的类型都是管道,(管道本质就是一个文件,可以进行读写操作),使用subprocess.PIPE来获取一个管道

# 输出
G:\Python\Python37\python3.exe G:/PythonWorkStation/Oldboy_8/day22/subprocess_test.py
 驱动器 G 中的卷是 Coding
 卷的序列号是 C14D-581B

 G:\PythonWorkStation 的目录

2019/05/24  19:57    <DIR>          .
2019/05/24  19:57    <DIR>          ..
2019/05/24  19:57               873 subprocess_test.py
2019/05/14  11:55               152 xlrd_test.py
2019/05/14  12:13               443 xlwt_test.py
2019/05/14  14:41               750 常用模块.md
2019/05/17  21:08    <DIR>          代码
               4 个文件          2,218 字节
               3 个目录 37,863,477,248 可用字节


Process finished with exit code 0

多条管道并存

p1 = subprocess.Popen("tasklist",shell=True,stdout=subprocess.PIPE)

p2 = subprocess.Popen("findstr QQ",shell=True,stdin=p1.stdout,stdout=subprocess.PIPE,stderr=subprocess.PIPE)

print(p2.stdout.read())
print(p2.stderr.read())

# 输出
b'QQProtect.exe                 3996 Services                   0     18,776 K\r\n'
b''

猜你喜欢

转载自www.cnblogs.com/tingguoguoyo/p/10920132.html
今日推荐