zoukankan      html  css  js  c++  java
  • hashlib hmac configparser subprocess xlrd xlwt

    hashlib模块:加密

    import hashlib
    # 基本使用
    cipher = hashlib.md5('需要加密的数据的二进制形式'.encode('utf-8'))
    print(cipher.hexdigest())  # 加密结果码
    
    # 加盐
    cipher = hashlib.md5()
    cipher.update('前盐'.encode('utf-8'))
    cipher.update('需要加密的数据'.encode('utf-8'))
    cipher.update('后盐'.encode('utf-8'))
    print(cipher.hexdigest())  # 加密结果码
    
    # 其他算法
    cipher = hashlib.sha3_256(b'')
    print(cipher.hexdigest())
    cipher = hashlib.sha3_512(b'')
    print(cipher.hexdigest())

    import hashlib

    m=hashlib.md5()# m=hashlib.sha256()

    m.update('hello'.encode('utf8'))
    print(m.hexdigest()) #5d41402abc4b2a76b9719d911017c592

    m.update('alvin'.encode('utf8'))

    print(m.hexdigest()) #92a7e713c30abbb0319fa07da2a5c4af

    m2=hashlib.md5()
    m2.update('helloalvin'.encode('utf8'))
    print(m2.hexdigest()) #92a7e713c30abbb0319fa07da2a5c4af

    '''
    注意:把一段很长的数据update多次,与一次update这段长数据,得到的结果一样
    但是update多次为校验大文件提供了可能。
    '''

    hmac  模块

    python 还有一个 hmac 模块,它内部对我们创建 key 和 内容 进行进一步的处理然后再加密:

    1 import hmac
    2 h = hmac.new('alvin'.encode('utf8'))
    3 h.update('hello'.encode('utf8'))
    4 print (h.hexdigest())#320df9832eab4c038b6c1d7ed73a5940
    # 必须加盐
    cipher = hmac.new(''.encode('utf-8'))
    cipher.update('数据'.encode('utf-8'))
    print(cipher.hexdigest())
    
    
    
    #要想保证hmac最终结果一致,必须保证:
    #1:hmac.new括号内指定的初始key一样
    #2:无论update多少次,校验的内容累加到一起是一样的内容
    
    import hmac
    
    h1=hmac.new(b'egon')
    h1.update(b'hello')
    h1.update(b'world')
    print(h1.hexdigest())
    
    h2=hmac.new(b'egon')
    h2.update(b'helloworld')
    print(h2.hexdigest())
    
    h3=hmac.new(b'egonhelloworld')
    print(h3.hexdigest())
    
    '''
    f1bf38d054691688f89dcd34ac3c27f2
    f1bf38d054691688f89dcd34ac3c27f2
    bcca84edd9eeb86f30539922b28f3981
    '''

    configparser模块

    # 注释1
    ; 注释2
    
    [section1]
    k1 = v1
    k2:v2
    user=egon
    age=18
    is_admin=true
    salary=31
    
    [section2]
    k1 = v1

    读取

    import configparser
    
    config=configparser.ConfigParser()
    config.read('a.cfg')
    
    #查看所有的标题
    res=config.sections() #['section1', 'section2']
    print(res)
    
    #查看标题section1下所有key=value的key
    options=config.options('section1')
    print(options) #['k1', 'k2', 'user', 'age', 'is_admin', 'salary']
    
    #查看标题section1下所有key=value的(key,value)格式
    item_list=config.items('section1')
    print(item_list) #[('k1', 'v1'), ('k2', 'v2'), ('user', 'egon'), ('age', '18'), ('is_admin', 'true'), ('salary', '31')]
    
    #查看标题section1下user的值=>字符串格式
    val=config.get('section1','user')
    print(val) #egon
    
    #查看标题section1下age的值=>整数格式
    val1=config.getint('section1','age')
    print(val1) #18
    
    #查看标题section1下is_admin的值=>布尔值格式
    val2=config.getboolean('section1','is_admin')
    print(val2) #True
    
    #查看标题section1下salary的值=>浮点型格式
    val3=config.getfloat('section1','salary')
    print(val3) #31.0

    改写

    import configparser
    
    config=configparser.ConfigParser()
    config.read('a.cfg',encoding='utf-8')
    
    
    #删除整个标题section2
    config.remove_section('section2')
    
    #删除标题section1下的某个k1和k2
    config.remove_option('section1','k1')
    config.remove_option('section1','k2')
    
    #判断是否存在某个标题
    print(config.has_section('section1'))
    
    #判断标题section1下是否有user
    print(config.has_option('section1',''))
    
    
    #添加一个标题
    config.add_section('egon')
    
    #在标题egon下添加name=egon,age=18的配置
    config.set('egon','name','egon')
    config.set('egon','age',18) #报错,必须是字符串
    
    
    #最后将修改的内容写入文件,完成最终的修改
    config.write(open('a.cfg','w'))
    import configparser
      
    config = configparser.ConfigParser()
    config["DEFAULT"] = {'ServerAliveInterval': '45',
                          'Compression': 'yes',
                         'CompressionLevel': '9'}
      
    config['bitbucket.org'] = {}
    config['bitbucket.org']['User'] = 'hg'
    config['topsecret.server.com'] = {}
    topsecret = config['topsecret.server.com']
    topsecret['Host Port'] = '50022'     # mutates the parser
    topsecret['ForwardX11'] = 'no'  # same here
    config['DEFAULT']['ForwardX11'] = 'yes'
    with open('example.ini', 'w') as configfile:
       config.write(configfile)
    
    基于上述方法添加一个ini文档
    添加ini

     suprocess模块

    import  subprocess
    
    '''
    sh-3.2# ls /Users/egon/Desktop |grep txt$
    mysql.txt
    tt.txt
    事物.txt
    '''
    
    res1=subprocess.Popen('ls /Users/jieli/Desktop',shell=True,stdout=subprocess.PIPE)
    res=subprocess.Popen('grep txt$',shell=True,stdin=res1.stdout,
                     stdout=subprocess.PIPE)
    
    print(res.stdout.read().decode('utf-8'))
    
    
    #等同于上面,但是上面的优势在于,一个数据流可以和另外一个数据流交互,可以通过爬虫得到结果然后交给grep
    res1=subprocess.Popen('ls /Users/jieli/Desktop |grep txt$',shell=True,stdout=subprocess.PIPE)
    print(res1.stdout.read().decode('utf-8'))
    
    
    #windows下:
    # dir | findstr 'test*'
    # dir | findstr 'txt$'
    import subprocess
    res1=subprocess.Popen(r'dir C:UsersAdministratorPycharmProjects	est函数备课',shell=True,stdout=subprocess.PIPE)
    res=subprocess.Popen('findstr test*',shell=True,stdin=res1.stdout,
                     stdout=subprocess.PIPE)
    
    print(res.stdout.read().decode('gbk')) #subprocess使用当前系统默认编码,得到结果为bytes类型,在windows下需要用gbk解码

    xlrd模块:excel读

                年终报表                
            教学部    市场部    咨询部    总计
    Jan-19    10        15        5    30
    Feb-19    10        15        5    30
    Mar-19    10        15        5    30
    Apr-19    10        15        5    30
    May-19    10        15        5    30
    Jun-19    10        15        5    30
    Jul-19    10        15        5    30
    Aug-19    10        15        5    30
    Sep-19    10        15        5    30
    Oct-19    10        15        5    30
    Nov-19    10        15        5    30
    Dec-19    10        15        5    30
    
    import xlrd
    # 读取文件
    work_book = xlrd.open_workbook("机密数据.xlsx")
    # 获取所有所有表格名称
    print(work_book.sheet_names())
    # 选取一个表
    sheet = work_book.sheet_by_index(1)
    # 表格名称
    print(sheet.name)
    # 行数
    print(sheet.nrows)
    # 列数
    print(sheet.ncols)
    # 某行全部
    print(sheet.row(6))
    # 某列全部
    print(sheet.col(6))
    # 某行列区间
    print(sheet.row_slice(6, start_colx=0, end_colx=4))
    # 某列行区间
    print(sheet.col_slice(3, start_colx=3, end_colx=6))
    # 某行类型 | 值
    print(sheet.row_types(6), sheet.row_values(6))
    # 单元格
    print(sheet.cell(6,0).value) # 取值
    print(sheet.cell(6,0).ctype) # 取类型
    print(sheet.cell_value(6,0)) # 直接取值
    print(sheet.row(6)[0])
    # 时间格式转换
    print(xlrd.xldate_as_datetime(sheet.cell(6, 0).value, 0))
    View Code

    xlwt模块:excel写

    import xlwt
    # 创建工作簿
    work = xlwt.Workbook()
    # 创建一个表
    sheet = work.add_sheet("员工信息数据")
    # 创建一个字体对象
    font = xlwt.Font()
    font.name = "Times New Roman"  # 字体名称
    font.bold = True  # 加粗
    font.italic = True  # 斜体
    font.underline = True  # 下划线
    # 创建一个样式对象
    style = xlwt.XFStyle()
    style.font = font
    keys = ['Owen', 'Zero', 'Egon', 'Liuxx', 'Yhh']
    # 写入标题
    for k in keys:
        sheet.write(0, keys.index(k), k, style)
    # 写入数据
    sheet.write(1, 0, 'cool', style)
    # 保存至文件
    work.save("test.xls")
    View Code

     复习模块

    # import datetime
    
    # print(datetime.datetime.now())
    # print(datetime.datetime.now()+datetime.timedelta(days=3))
    # print(datetime.datetime.now()+datetime.timedelta(seconds=111))
    
    # 2019-04-20 20:00:45.964735
    # 2019-04-23 20:00:45.964735
    # 2019-04-20 20:02:36.964735
    
    # current_time=datetime.datetime.now()
    # print(current_time.replace(year=1977))
    # 1977-04-20 20:02:01.534058
    
    # print(datetime.date.fromtimestamp(11111111))
    # 时间戳直接转成日期格式 1970-05-09
    
    
    
    
    # 打印进度条
    
    # print('[%-50s]' %'#')
    # print('[%-50s]' %'##')
    # print('[%-50s]' %'###')
    # [#                                                 ]
    # [##                                                ]
    # [###                                               ]
    
    # num=30
    # print('%s%%'%num)
    # 30% 第一个%是取消第二个%的特殊意义的
    
    # width=30
    # print(('[%%-%ds]'%width)%'#')
    # print(('[%%-%ds]'%width)%'##')
    # print(('[%%-%ds]'%width)%'###')
          #  [%-(width)s] %#
    # [#                             ]
    # [##                            ]
    # [###                           ]
    
    # def progress(percent,width=50):
    #     if percent>1:
    #         percent=1
    #     show_str=('[%%-%ds]'%width) %(int(width*percent)*'#')
    #     print('
    %s %d%%'%(show_str,int(100*percent)),end='')
    #
    # import time
    # recv_size=0
    # total_size=8097
    # while recv_size<total_size:
    #     time.sleep(0.1)
    #     recv_size+=576
    #     percent=recv_size/total_size
    #     progress(percent)
    
    # import shutil
    # import time
    # ret=shutil.make_archive(
    #     'E:代码存放位置第五周%s'%time.strftime('%Y-%m-%d'),
    #     'gztar',
    #     root_dir=r'E:代码存放位置第五周继承.py'
    # )
    
    
    
    
    # import shelve
    # info1={'age':18,'height':180,'weight':80}
    # info2={'age':73,'height':160,'weight':80}
    #
    # d=shelve.open('db.shv')
    # d['egon']=info1
    # d['alex']=info1
    # d.close()
    
    # d=shelve.open('db.shv')
    # print(d['egon'])
    # print(d['alex'])
    # d.close()
    # {'age': 18, 'height': 180, 'weight': 80}
    # {'age': 18, 'height': 180, 'weight': 80}
    
    #
    # d=shelve.open('db.shv',writeback=True)
    # d['alex']['age']=1000
    # print(d['alex'])
    # d.close()
    # {'age': 1000, 'height': 180, 'weight': 80}
    
    # d=shelve.open('db.shv')
    # print(d['alex'])
    # d.close()
    # {'age': 1000, 'height': 180, 'weight': 80}
    
    
    
    
    
    # ==========================================查
    # import xml.etree.cElementTree as ET
    #
    # tree=ET.parse('a.xml')
    # root=tree.getroot()
    # print(root.tag)
    # data
    # 三种查找节点的方式
    # res=root.iter('rank')  #会在整个树中进行查找,而且是查找到所有
    # for item in res:
        # print(item)
        # print('='*50)
        # print(item.tag) #标签名
        # print(item.attrib) #属性
        # print(item.text) #文本内容
        # == == == == == == == == == == == == == == == == == == == == == == == == ==
        # rank
        # {'updated': 'yes'}
        # 2
        # == == == == == == == == == == == == == == == == == == == == == == == == ==
        # rank
        # {'updated': 'yes'}
        # 5
        # == == == == == == == == == == == == == == == == == == == == == == == == ==
        # rank
        # {'updated': 'yes'}
        # 69
    
    # res=root.find('country') #只能在当前元素的下一级开始查找,并且只找到一个就结束
    # print(res.tag)
    # print(res.attrib)
    # print(res.text)
    # country
    # {'name': 'Liechtenstein'}
    # nb=res.find('neighbor') #在当前country的节点往下查找 找到只找到一个就结束
    # print(nb.attrib)
    # {'name': 'Austria', 'direction': 'E'}
    
    # cy=root.findall('country')  #只能在当前元素的下一级开始查找
    # print([item.attrib for item in cy])
    # [{'name': 'Liechtenstein'}, {'name': 'Singapore'}, {'name': 'Panama'}]
    
    # # -=====================================改
    # import xml.etree.ElementTree as ET
    # tree=ET.parse('a.xml')
    # root=tree.getroot()
    #
    # for year in root.iter('year'):  #会在整个树中进行查找,而且是查找所有的
    #     year.text=str(int(year.text)+10)
    #     year.attrib={'updated':'yes'}
    #
    # tree.write('b.xml')
    # tree.write('a.xml')
    
    # -=====================================增
    # import xml.etree.ElementTree as ET
    # tree=ET.parse('a.xml')
    # root=tree.getroot()
    #
    # for country in root.iter('country'):
    #     # print(country)
    #     year=country.find('year')
    #     # print(year)
    #     if int(year.text)>2000:
    #         # print(country.attrib)
    #         ele=ET.Element('egon')
    #         ele.attrib={'nb':'yes'}
    #         ele.text='非常帅'
    #         country.append(ele)
    #         # country.remove(year)
    # tree.write('b.xml')
    
    
    
    
    
    
    # import os
    # while True:
    #     cmd=input('>>>: ').strip()
    #     if not  cmd:continue
    #     # print('%s run'%cmd)
    #     res=os.system(cmd)  #dir
    
        # network.send(res)
    
    
    # import subprocess  #运行系统命令 允许控制命令的结果是打印到屏幕上还是做其他的事情
    # obj=subprocess.Popen('dir',  #正确命令
    #                      shell=True, #命令解释器
    #                      stdout=subprocess.PIPE, #正确管道
    #                      stderr=subprocess.PIPE #错误管道
    # )
    #
    # res1=obj.stdout.read()
    # print('正确结果111: ',res1.decode('gbk'))
    #
    # res2=obj.stdout.read()
    # print('正确结果222: ',res2.decode('gbk')) #只能取走一次,取走了正确管道里就没有信息了
    # #
    # res2=obj.stderr.read() #只解读命令
    # print('错误结果: ',res2.decode('gbk'))
    #
    
    
    
    import configparser #解析配置 ini这种格式文件里面的组成形式
    config=configparser.ConfigParser()
    config.read('my.ini')
    
    # secs=config.sections() #标题
    # print(secs)
    # ['egon', 'lqz']
    
    # print(config.options('egon'))
    # ['age', 'pwd', 'sex', 'salary', 'is_beautiful']
    
    # age=config.get('egon','age')
    # print(age,type(age)) #18 <class 'str'>
    # age=config.getint('egon','age')
    # print(age,type(age)) #18 <class 'int'>
    
    # salary=config.getfloat('egon','salary')
    # print(salary,type(salary)) #5.1 <class 'float'>
    
    b=config.getboolean('egon','is_beautiful')
    print(b,type(b))  #True <class 'bool'>
    复习 模块
  • 相关阅读:
    Ubuntu下的解压缩
    Android开机动画
    Android 5.0源码编译问题
    ubuntu学习的简单笔记
    全局变量:global与$GLOBALS的区别和使用
    Java语言中的面向对象特性总结
    c/c++常见面试题
    查数据库中的表,了解大体结构
    PHP数组详解
    HTML5新增及移除的元素
  • 原文地址:https://www.cnblogs.com/lakei/p/10717708.html
Copyright © 2011-2022 走看看