当前位置: 移动技术网 > IT编程>脚本编程>Python > day21(configparser ,subprocess , xlrd ,xlwt 模块)

day21(configparser ,subprocess , xlrd ,xlwt 模块)

2019年05月15日  | 移动技术网IT编程  | 我要评论

暴戾王爷的妾奴,马尔代夫旅游费用,芙蓉花图片

一,configparser模块

'''
configparser模块:
是什么: 用于解析配置文件的模块 配置文件的定义: 用于编写保存某个软件或某个系统的一系列参数的文件 设置参数 为什么需要配置文件: 无论是什么样的软件应用程序,在执行过程中,都需要很多的参数 而一些参数经常会需要修改 例如:qq里面的下载路径 atm中的错误次数 如果直接写死在程序中,使用者在需要修改参数时,就不得不直接修改源代码 这是非常不合理的,所以我们通常还会把这些需要变化的参数提取出来放到配置文件中 ''''' #打开配置文件来读取参数 # with open('atm.cfg','r')as f: # err_count = int(f.read()) # print(err_count,type(err_count)) import configparser #创建解析对象 c = configparser.configparser() c.read('atm.cfg',encoding='utf-8') #读取指定的配置文件 #获取一个配置项 count = int(c.get('atm','err_count')) print(int(count)) print(type(count)) temp_count = 0 while true: if temp_count >= count: print('该账号已经被锁定') break name = input('name:') pwd = input('pwd:') if name == 'owen' and pwd == '123': print('登录成功') break else: print('账号或密码不正确!') temp_count += 1
import configparser

# 创建解析对象
c = configparser.configparser()
c.read('atm.cfg',encoding='utf-8')

#获取所有分区名称
print(c.sections())             #['atm', 'mysql', 'mysqlid']

#某个分区下所有option名字
print(c.options('mysql'))       #['name', 'pwd']

#判断某个分区是否存在
print(c.has_section('mysql'))   #true

#判断某个选项是否存在
print(c.has_option('mysql','name'))     #true

# 封装了类型转换的方法
count = c.getint('atm','err_count')
# c.getboolean()
# c.getfloat()
print(count,type(count))        #3 <class 'int'>


#设置某个选项的值,如果option已经存在则覆盖
c.set('atm','test','666')
#添加一个新分区,如果分区存在会报错
c.add_section('atm')



print(list(c.keys()))           #['default', 'atm', 'mysql', 'mysqlid']
print(list(c.values())[1].name) #atm

#通过get获取里面的值
print(c.get('atm','test'))
print(c.getint('atm','err_count'))


print(list(c.values()))         #[<section: default>, <section: atm>, <section: mysql>, <section: mysqlid>]
#dir 可以查看某个对象所有可用的属性 __开头不要管,系统自带的
print(dir(list(c.values())[1]))

#写入数据到文件
with open('atm.cfg','wt',encoding='utf-8')as w:
    c.write(w)




# 创建 解析对象,读取指定的配置文件
c = configparser.configparser()
c.read('atm.cfg',encoding='utf-8')

# 设置某个选项的值 如果option以及存在则覆盖
c.set('atm1','aaa','111')

#添加
c.add_section('atm_test')
c.set('atm_test','www','https')

#写入数据到文件
with open('atm.cfg','wt',encoding='utf-8')as w:
    c.write(w)
#代码生成配置文件

import configparser
c = configparser.configparser()

c.add_section('test')
c.set('test','name','jock')

with open('test.cfg','wt',encoding='utf-8')as w:
    c.write(w)
'''
总结:
    configparser:用来解析配置文件的
    一:对配置文件有格式要求:
        1,只能由分区section和选区option
        2,不能有重复的section,同一个section,不能有重复的option
        3,不区分数据类型,都是字符串
        4,任何option都必须包含在section中
    
    二:需要掌握的方法:
        read('文件路径','编码')
        get('分区名称','选项名称') 返回的是字符串
        getint  getfloat  getboolean
             
'''

 

二,subprocess模块

'''
subprocess:子进程
1,什么是进程:
        指的是一个正在运行中的程序
        子进程指的是由另一个进程开启的进程,a在运行过程中开启了b ,b就是a的子进程
2,为什么要开启子进程:
当一个程序在运行过程中有一个任务,自己做不了或是不想做,就可以开启另一个进程来帮助其完成任务
例如:qq中收到一个链接,点击链接,就开启了浏览器,浏览器就是qq的子进程

可以理解为用于执行系统指令的模块
'''''

import subprocess
import  os
# os.system('dir')  #系统指令

'''
内存中,每个进程的内存区域是相互隔离的不能直接访问,所以需要管道来通讯
stdout = subprocess.pipe就是指定了一个输出管道
p = subprocess.popen('dir',shell=true,stdout=subprocess.pipe) 从管道中读取出执行结果
result = p.stdout.read().decode('gbk')还需要设定编码格式
'''

#三个管道
p1 = subprocess.popen('dir',shell=true,stdout=subprocess.pipe,stderr=-1)
# winds  默认是gbk,所以需要指定编码格式
print(p1.stdout.read().decode('gbk'))

p2 = subprocess.popen('disr',shell=true,stdout=subprocess.pipe,stderr=-1)
#打印错误信息
print(p1.stderr.read().decode('gbk'))


#案例:
# tasklist | findstr python    #先执行tasklist 把结果交给 findstr来处理

p1 = subprocess.popen('tasklist',shell=true,stdout=subprocess.pipe)
p2 =subprocess.popen('findstr python',shell=true,stdin=p1.stdout,stdout=subprocess.pipe
                     ,stderr=subprocess.pipe)
#打印进程信息
print(p2.stdout.read().decode('gbk'))
print(p2.stderr.read().decode('gbk'))


'''
后期项目:cmdb,需要收集服务器的信息,比如内存信息

总结:
    subprocess 需要掌握的方法:
    1,参数  指令
    2,是否是一个指令
    3,错误输出管道
    4,输入管道
    5,输出管道
    p = subprocess.popen('你的指令或是某个exe',shell=true,stdout=,stdin=,stderr=)
    取出管道中的数据
    p.stdout.read().encode()
    p.stderr.read()
    将输入数据写入管道,交给对方进程
    p.stdin.write(p.stdout.read())
    
    当你需要执行系统命令时,你需要想到它
'''

 

三,xlrd模块

import xlrd

workbook = xlrd.open_workbook('机密数据.xlsx')
#查看所有工作表的名称
print(workbook.sheet_names())       #['sheet1', 'sheet2', 'sheet3']

#获取某个工作表
sheet = workbook.sheet_by_index(1)
print(sheet.name)                   #sheet2

sheet = workbook.sheet_by_name('sheet1')
print(sheet.name)               #sheet1

#获取某一行
row = sheet.row(2)
print(row)              #[text:'张三', number:23.0, text:'男', number:180.0, empty:'']

#获取单元格
cell = row[0]
#单元格的数据类型
print(cell.ctype)       #1
#单元格的数据
print(cell.value)       #张三

#转换日期类型
print(str(xlrd.xldate_as_datetime(cell.value,0)))

#获取表格的列数
print(sheet.ncols)      #5
#获取表格的行数
print(sheet.nrows)      #6

#获取第一行的单元格的个数
print(sheet.row_len(1))     #5

#某个单元格的数据,索引从0开始
print(sheet.cell(0,0))      #text:'机密数据表'
print(sheet.cell(3,0))      #text:'李四'

#将数据读取出来变成python的数据类型 [{},{},{}]

#案例:将每个数据读取为python数据类型
#最后的列表
li = []
#先拿出所有的列名称
keys = sheet.row_values(1)
print(keys)         #['姓名', '年龄', '性别', '成绩', '时间']

for i in range(2,sheet.nrows):
    print(i)
    row = sheet.row(i)
    print(row)          #[text:'张三', number:23.0, text:'男', number:180.0, text:' 2010/01/01']

    #直接取出所有值
    row = sheet.row_values(i)
    print(row)             #['张三', 23.0, '男', 180.0, ' 2010/01/01']

    #创建一个空字典
    dic = {}
    for k in keys:
        print(k)
        #每次拿出一个key 与一个value --对应
        dic[k] = row[keys.index(k)]
        if k == '生日':
            #如果是生日字段,需要转换时间类型
            dic[k] = str(xlrd.xldate_as_datetime(row[keys.index(k)],0))
    li.append(dic)
print(li) #[{'姓名': '张三', '年龄': 23.0, '性别': '男', '成绩': 180.0, '生日': '2001-01-02 00:00:00'},{.....]
''' 总结: xlrd 模块是用于读取表格数据的 xlrd 是一个第三方的需要自己安装,可以在终端: pip install xlrd 打开文件: wb wb = xlrd.open_workbook('文件路径') 获取路径: sheet = wb.sheet_by_name() sheet = wb.sheet_by_index() 获取行数: sheet.nrows() 获取列数: sheet.ncols() 取某行数据 sheet.row_value(行索引) 获取某单元格的数据 sheet.cell(行,列).value '''

 

四,xlwt模块

import xlwt

#xlwt 是第三方用于生成一个exel表格

#1,创建一个工作簿
wb = xlwt.workbook()

#2,创建一个工作表
sheet = wb.add_sheet('特工信息')   #type:xlwt.worksheet

#字体对象
font = xlwt.font()
font.bold = true

#style样式对象
style = xlwt.xfstyle()
style.font = font       #将字体设置到样式中

#写入数据
# sheet.write(0,0,'这是标题')
#写入并合并单元格
sheet.write_merge(0,0,0,4,'这是标题',style)

#将工作簿写入到文件
wb.save('abc.xls')

#将数据写入到表格中

import xlwt
data = [{'name': '哈利波特', '代号': 1.0, 'gender': 'man', 'age': 18.0,'生日': '2001-01-01 00:00:00'},
        {'name': 'owen', '代号': 748.0, 'gender': 'woman', 'age': 68.0, '生日': '1950-01-01 00:00:00'},
        {'name': 'jerry', '代号': 168.0, 'gender': 'man', 'age': 18.0,'生日': '2001-01-01 00:00:00'}]

#创建工作簿
wb = xlwt.workbook()

#创建工作表
sheet = wb.add_sheet('特工信息')

#写入标题
sheet.write_merge(0,0,0,4,'特工信息表')

#写入列名称
keys = data[0].keys()
i = 0
for k in keys:
    sheet.write(1,i,k)
    i += 1

#写入数据
for dic in data:
    values = list(dic.values())

    row_index = 2 + data.index(dic)

    for v in values:
        sheet.write(row_index,values.index(v),v)

#保存文件
wb.save('机密数据副本.xls')


'''
xlwt 用于将数据写入到表格中
使用到的几个函数:
    1,创建工作簿
        wb = xlwt.workbook()
    2,创建工作表
        sheet = wb.add_sheet('sheet名字')
    3,写入数据
        sheet.write(行,列,数据)
    4,保存到文件
        wb.save('路径')
    
'''

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网