subprocess模块

今日内容

1 subprocess模块

自动化运维平台CMDB会用到!!!

subprocess模块允许你去创建一个新的进程让其执行另外的程序,并与它进行通信,

获取 标准的输入标准输出、标准错误 以及 返回码 等。更多查看官网:subprocess

特点:执行系统命令的模块,系统执行完的结果,能够获得到,速度快。

# subprocess模块:执行系统命令的模块,系统执行完的结果,能够获得到,速度快
'''
subprocess模块允许你去创建一个新的进程让其执行另外的程序,
并与它进行通信,获取标准的输入、标准输出、标准错误以及返回码等
'''

import subprocess

# shell=True,新开了终端,执行ls命令
# 开启一个进程,打开一个终端,执行dir命令,执行完的正确输出放到了一个管道里,执行出错了也放到管道里
# res=subprocess.Popen('ls',shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)

'''从这个进程中取到新开的进程的结果,通过stdout去管道中读出成功的内容;
读出来是bytes格式,如果是window平台,需要使用gbk解码。
linux和mac就是utf-8 '''
print(str(res.stdout.read(), encoding='gbk'))
print(str(res.stderr.read(), encoding='gbk'))

"""查看当前路径有哪些文件,然后再过滤出xmltest.xml"""
# ls |grep xmltest.xml ---》 windows平台用
# dir|findstr xmltest.xml ----》linux平台用
# 一个的执行结果是另一个的输入
res = subprocess.Popen('dir', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# print(str(res.stdout.read(),encoding='gbk'))
# 上面一句话,会往管道中放入一堆字符串,取一次就没了
# print('dddd')
# print(str(res.stdout.read(),encoding='gbk'))
res2 = subprocess.Popen('findstr xml*', shell=True, stdin=res.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# import time  # 如果使用了time.sleep(1)第二个print(str...))就会打印一秒后拿到的数据。
# time.sleep(1)
print(str(res.stdout.read(), encoding='gbk'))
#
print(str(res2.stdout.read(), encoding='gbk'))



# ls |gerp xml

res=subprocess.Popen('dir | findstr xml*',shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)

# print(str(res.stdout.read(),encoding='gbk'))
# print('xxxx')
# print(str(res.stderr.read(),encoding='gbk'
))

print(res.stdout.read().decode('gbk'))
原文地址:https://www.cnblogs.com/bbdbolg/p/14295830.html