第八章 Python之常用模块

日志模块

import logging

import logging

#默认级别为warning,默认打印到终端
logging.debug('debug')      #10
logging.info('info')        #20
logging.warning('warn')     #30
logging.error('error')      #40
logging.critical('critical')#50
可在logging.basicConfig()函数中通过具体参数来更改logging模块默认行为,可用参数有
filename:用指定的文件名创建FiledHandler(后边会具体讲解handler的概念),这样日志会被存储在指定的文件中。
filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
format:指定handler使用的日志显示格式。
datefmt:指定日期时间格式。
level:设置rootlogger(后边会讲解具体概念)的日志级别
stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件,默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。

#格式
%(name)s:Logger的名字,并非用户名,详细查看

%(levelno)s:数字形式的日志级别

%(levelname)s:文本形式的日志级别

%(pathname)s:调用日志输出函数的模块的完整路径名,可能没有

%(filename)s:调用日志输出函数的模块的文件名

%(module)s:调用日志输出函数的模块名

%(funcName)s:调用日志输出函数的函数名

%(lineno)d:调用日志输出函数的语句所在的代码行

%(created)f:当前时间,用UNIX标准的表示时间的浮 点数表示

%(relativeCreated)d:输出日志信息时的,自Logger创建以 来的毫秒数

%(asctime)s:字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒

%(thread)d:线程ID。可能没有

%(threadName)s:线程名。可能没有

%(process)d:进程ID。可能没有

%(message)s:用户输出的消息
logging.basicConfig详细解释
logging.basicConfig(filename='access.log',
                    format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S %p',
                    level=10)
import logging
#介绍
#logging模块的Formatter,Handler,Logger,Filter对象
#Logger:产生日志的对象
logger1=logging.getLogger('访问日志')
#Filter:过滤日志的对象
#Handler:接收日志然后控制打印到不同的地方,FileHandler用来打印到文件中,#StreamHandler用来打印到终端
h1=logging.StreamHandler()
h2=logging.FileHandler('access.log',encoding='utf-8')
#Formatter对象:可以定制不同的日志格式对象,然后绑定给不同的Handler对象使用,以此来控制不同的Handler的日志格式
formatter1=logging.Formatter(
        fmt='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S %p',)

#使用
#logger负责产生日志,交给Filter过滤,然后交给不同的Handler输出,handler需要绑定日志格式
h1.setFormatter(formatter1)
h2.setFormatter(formatter1)
logger1.addHandler(h1)
logger1.addHandler(h2)
logger1.setLevel(10)
h1.setLevel(20)         #Handler的日志级别设置应该高于Logger设置的日志级别
logger1.debug('debug')
logger1.info('info')
logger1.warning('warning')
logger1.error('error')
logger1.critical('critical')
logging模块的Formatter,Handler,Logger,Filter对象
#应用
import os
import logging.config

# 定义三种日志输出格式 开始

standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' 
                  '[%(levelname)s][%(message)s]' #其中name为getlogger指定的名字

simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'

id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'

# 定义日志输出格式 结束

logfile_dir = os.path.dirname(os.path.abspath(__file__))  # log文件的目录

logfile_name = 'all2.log'  # log文件名

# 如果不存在定义的日志目录就创建一个
if not os.path.isdir(logfile_dir):
    os.mkdir(logfile_dir)

# log文件的全路径
logfile_path = os.path.join(logfile_dir, logfile_name)

# log配置字典
LOGGING_DIC = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': standard_format
        },
        'simple': {
            'format': simple_format
        },
    },
    'filters': {},
    'handlers': {
        #打印到终端的日志
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',  # 打印到屏幕
            'formatter': 'simple'
        },
        #打印到文件的日志,收集info及以上的日志
        'default': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件
            'formatter': 'standard',
            'filename': logfile_path,  # 日志文件
            'maxBytes': 1024*1024*5,  # 日志大小 5M
            'backupCount': 5,
            'encoding': 'utf-8',  # 日志文件的编码,再也不用担心中文log乱码了
        },
    },
    'loggers': {
        #logging.getLogger(__name__)拿到的logger配置
        '': {
            'handlers': ['default', 'console'],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
            'level': 'DEBUG',
            'propagate': True,  # 向上(更高level的logger)传递
        },
    },
}


def load_my_logging_cfg():
    logging.config.dictConfig(LOGGING_DIC)  # 导入上面定义的logging配置
    logger = logging.getLogger(__name__)  # 生成一个log实例
    logger.info('It works!')  # 记录该文件的运行状态

if __name__ == '__main__':
    load_my_logging_cfg()
logging配置文件

正则模块

import re

  正则就是用一些具有特殊含义的符号组合到一起(称为正则表达式)来描述字符或者字符串的方法

# re模块的方法
print(re.findall('a[-+/*]b','axb azb aAb a+b a-b'))
# re.search()
print(re.search('a[-+/*]b','axb azb aAb a+b a-b'))  #有结果返回一个对象,无结果返回None
print(re.search('a[-+/*]b','axb azb aAb a+b a-b').group())  #group()方法只匹配成功一次就返回
#re.match()
print(re.match('a[-+/*]b','axb azb aAb a+b a-b'))  #从头开始取,无结果返回None
print(re.match('a[-+/*]b','a*b azb aAb a+b a-b').group())
#re.split()
print(re.split(':','root:x:0:0::/root',maxsplit=1))
#re.sub()
print(re.sub('root','admin','root:x:0:0::/root',1))
print(re.sub('^([a-z]+)([^a-z]+)(.*?)([^a-z]+)([a-z]+)$',r'52341','root:x:0:0::/bash'))
#re.compile()
obj=re.compile('ad{2}b')
print(obj.findall('a12b a123b a124a a82b'))
print(obj.search('a12b a123b a124a a82b'))
# w 匹配字母数字及下划线
print(re.findall('w','lary 123 + _ - *'))
# W 匹配非字母数字及下划线
print(re.findall('W','lary 123 + _ - *'))
# s 匹配任意空白字符
print(re.findall('s','lary	n 123
3 + _ - *'))
# S 匹配任意非空字符
print(re.findall('S','lary	n 123
3 + _ - *'))
# d 匹配任意数
print(re.findall('d','lary	n 123
3 + _ - *'))
# D 匹配任意非数字
print(re.findall('D','lary	n 123
3 + _ - *'))
# 
 匹配一个换行符
print(re.findall('
','lary	n 123
3 + _ - *'))
# 	 匹配一个制表符
print(re.findall('	','lary	n 123
3 + _ - *'))
# ^  匹配字符串开头
print(re.findall('^e','elary	n 123
3 ego + _ - *'))
# $  匹配字符串的末尾
print(re.findall('o$','elary	n 123
3 ego + _ - *o'))
# .  匹配任意一个字符(除了换行符)
print(re.findall('a.b','a1b a b a-b aaaab'))
# ?  匹配0个或1个由前面的正则表达式定义的片段,非贪婪方式
print(re.findall('ab?','a ab abb abbb a1b'))
# *  匹配0个或多个的表达式
print(re.findall('ab*','a ab abb abbb a1b'))
# +  匹配1个或多个的表达式
print(re.findall('ab+','a ab abb abbb a1b'))
# {n,m}匹配n到m次由前面的正则表达式定义的片段,贪婪方式
print(re.findall('ab{0,1}','a ab abb abbb a1b'))
print(re.findall('ab?','a ab abb abbb a1b'))
print(re.findall('ab{2,3}','a ab abb abbb a1b'))
#.*?匹配任意个字符,非贪婪方式
print(re.findall('a.*?b','a123b456b'))
#.* 匹配任意个字符,贪婪方式
print(re.findall('a.*b','a123b456b'))
# a|b 匹配a或b
print(re.findall('compan(ies|y)','too many companies shut down,and the next is my company'))
print(re.findall('compan(?:ies|y)','too many companies shut down,and the next is my company'))
# [...] 表示一组字符,取括号中任意一个字符
print(re.findall('a[a-z]b','axb azb aAb a+b a-b'))
print(re.findall('a[a-zA-Z]b','axb azb aAb a+b a-b'))
print(re.findall('a[-+/*]b','axb azb aAb a+b a-b'))  #-应该写在[]中的两边
# [^...]不在[]中的字符
print(re.findall('a[^-+/*]b','axb azb aAb a+b a-b'))
# (n)精确匹配n个前面表达式
# () 匹配括号内的表示式,也表示一个组
# A 匹配字符串开始
#  匹配字符串结束,如果存在换行,只匹配到换行前的结束字符串
# z 匹配字符串结束
# G 匹配最后匹配完成的位置

print(re.findall(r'a\c','ac alc aBc')) #r''代表原生表达式
正则表达式

time模块

import time

import time

print(time.time())      #时间戳
print(time.localtime()) #本地时区时间
print(time.gmtime())    #标准时间
print(time.strftime("%Y-%m-%d %X"))    #格式化时间

import datetime

print(datetime.datetime.now())
print(datetime.datetime.fromtimestamp(11111))
print(datetime.datetime.now()+datetime.timedelta(days=3))
print(datetime.datetime.now().replace(year=1999))

  第八章 Python之常用模块

1 #--------------------------按图1转换时间
 2 # localtime([secs])
 3 # 将一个时间戳转换为当前时区的struct_time。secs参数未提供,则以当前时间为准。
 4 time.localtime()
 5 time.localtime(1473525444.037215)
 6
 7 # gmtime([secs]) 和localtime()方法类似,gmtime()方法是将一个时间戳转换为UTC时区(0时区)的struct_time。
 8
 9 # mktime(t) : 将一个struct_time转化为时间戳。
10 print(time.mktime(time.localtime()))#1473525749.0
11
12
13 # strftime(format[, t]) : 把一个代表时间的元组或者struct_time(如由time.localtime()和
14 # time.gmtime()返回)转化为格式化的时间字符串。如果t未指定,将传入time.localtime()。如果元组中任何一个
15 # 元素越界,ValueError的错误将会被抛出。
16 print(time.strftime("%Y-%m-%d %X", time.localtime()))#2016-09-11 00:49:56
17
18 # time.strptime(string[, format])
19 # 把一个格式化时间字符串转化为struct_time。实际上它和strftime()是逆操作。
20 print(time.strptime('2011-05-05 16:37:06', '%Y-%m-%d %X'))
21 #time.struct_time(tm_year=2011, tm_mon=5, tm_mday=5, tm_hour=16, tm_min=37, tm_sec=6,
22 #  tm_wday=3, tm_yday=125, tm_isdst=-1)
23 #在这个函数中,format默认为:"%a %b %d %H:%M:%S %Y"。
View Code

第八章 Python之常用模块

1 #--------------------------按图2转换时间
2 # asctime([t]) : 把一个表示时间的元组或者struct_time表示为这种形式:'Sun Jun 20 23:21:05 1993'。
3 # 如果没有参数,将会将time.localtime()作为参数传入。
4 print(time.asctime())#Sun Sep 11 00:43:43 2016
5
6 # ctime([secs]) : 把一个时间戳(按秒计算的浮点数)转化为time.asctime()的形式。如果参数未给或者为
7 # None的时候,将会默认time.time()为参数。它的作用相当于time.asctime(time.localtime(secs))。
8 print(time.ctime())  # Sun Sep 11 00:46:38 2016
9 print(time.ctime(time.time()))  # Sun Sep 11 00:46:38 2016
View Code

random模块

import random

import random

print(random.random())          #大于0小于1之间的小数
print(random.randint(1,3))      #大于1且小于等于3之间的整数(包括头尾)
print(random.randrange(1,3))    #大于1且小于等于3之间的整数(顾头不顾尾)
print(random.choice([1,'hell',3]))   #取其中一个
print(random.sample([1,2,3],2)) #取任意两个组合
print(random.uniform(1,4))      #取1-4之间的小数

l=[1,2,3,4,5]
random.shuffle(l)       #打乱原来的顺序
print(l)
#随机验证码小功能
def make_code(n):
    res=''
    for i in range(n):
        s1=str(random.randint(0,9))
        s2=chr(random.randint(65,90))
        res+=random.choice([s1,s2])
    return res

res=make_code(6)
print(res)
View Code

os模块

import os

os.path.abspath(path)  #返回path规范化的绝对路径
os.path.dirname(path)  #返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.exists(path)  #如果path存在,返回True;如果path不存在,返回False
os.path.join(path1[, path2[, ...]])  #将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
os.getcwd() #获取当前工作目录,即当前python脚本工作的目录路径
os.chdir("dirname")  #改变当前脚本工作目录;相当于shell下cd
os.curdir  #返回当前目录: ('.')
os.pardir  #获取当前目录的父目录字符串名:('..')
os.makedirs('dirname1/dirname2')    #可生成多层递归目录
os.removedirs('dirname1')    #若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir('dirname')    #生成单级目录;相当于shell中mkdir dirname
os.rmdir('dirname')    #删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
os.listdir('dirname')    #列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
os.remove()  #删除一个文件
os.rename("oldname","newname")  #重命名文件/目录
os.stat('path/filename')  #获取文件/目录信息
os.sep    #输出操作系统特定的路径分隔符,win下为"\",Linux下为"/"
os.linesep    #输出当前平台使用的行终止符,win下为"	
",Linux下为"
"
os.pathsep    #输出用于分割文件路径的字符串 win下为;,Linux下为:
os.name    #输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
os.system("bash command")  #运行shell命令,直接显示
os.environ  #获取系统环境变量
os.path.split(path)  #将path分割成目录和文件名二元组返回
os.path.basename(path)  #返回path最后的文件名。如何path以/或结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.isabs(path)  #如果path是绝对路径,返回True
os.path.isfile(path)  #如果path是一个存在的文件,返回True。否则返回False
os.path.isdir(path)  #如果path是一个存在的目录,则返回True。否则返回False
os.path.getatime(path)  #返回path所指向的文件或者目录的最后存取时间
os.path.getmtime(path)  #返回path所指向的文件或者目录的最后修改时间
os.path.getsize(path) #返回path的大小
View Code
#在Linux和Mac平台上,该函数会原样返回path,在windows平台上会将路径中所有字符转换为小写,并将所有斜杠转换为反斜杠。
print(os.path.normcase('c:/windows\system32\'))
#规范化路径,如..和 /
print(os.path.normpath('c://windows\System32\../Temp/'))
a = '/Users/jieli/test1/\a1/\\aa.py/../..'
print(os.path.normpath(a))
#os路径处理
#方式一:
import os,sys
Base_dir = os.path.normpath(os.path.join(
    os.path.abspath(__file__),
    os.pardir, #上一级
    os.pardir,
    os.pardir
))
print(Base_dir)

#方式二:
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

sys模块

import sys

import sys

sys.argv        #命令行参数List,第一个元素是程序本身路径
sys.exit(n)     #退出程序,正常退出时exit(0)
sys.version     #获取Python解释程序的版本信息
sys.maxint      #最大的Int值
sys.path        #返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform    #返回操作系统平台名称
def process(percent,width=50):
    if percent >=1:
        percent=1
    show_str=('[%%-%ds]'%width)%('+'*int(width*percent))
    print('
%s %d%%'%(show_str,percent*100),end='')

recv_size=0
total_size=10241
while recv_size < total_size:
    time.sleep(0.1)
    recv_size+=1024
    process(recv_size/total_size)
打印进度条

shutil模块

import shutil

shutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w')) #将文件内容拷贝到另一个文件中
shutil.copyfile('f1.log', 'f2.log')     #拷贝文件,目标文件无需存在
shutil.copymode('f1.log', 'f2.log')     #仅拷贝权限。内容、组、用户均不变,目标文件必须存在
shutil.copystat('f1.log', 'f2.log')     #仅拷贝状态的信息,包括:mode bits, atime, mtime, flags,目标文件必须存在
shutil.copy('f1.log', 'f2.log')         #拷贝文件和权限
shutil.copy2('f1.log', 'f2.log')        #拷贝文件和状态信息
#递归的去拷贝文件夹,目标目录不能存在,注意对folder2目录父级目录要有可写权限,ignore的意思是排除
shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))
shutil.rmtree('folder1')                #递归的去删除文件
shutil.move('folder1', 'folder3')       #递归的去移动文件
shutil.make_archive("data_bak", 'gztar', root_dir='/data')  #将 /data 下的文件打包放置当前程序目录
shutil.make_archive("/tmp/data_bak", 'gztar', root_dir='/data') #将 /data下的文件打包放置 /tmp/目录

json&pickle模块

import json

import pickle

   序列化:我们把对象(变量)从内存中变成可存储或传输的过程称之为序列化

  序列化的目的:在断电或重启程序之前将程序当前内存中所有数据都保存下来,以便于下次程序执行能够从文件中载入之前的数据;序列化之后,不仅可以把序列化后的内容写入磁盘,还可以通过网络传输到别的机器上,如果收发的双方约定好实用一种序列化的格式,那么便打破了平台/语言差异化带来的限制,实现了跨平台数据交互

  序列化之json

  json表示的对象就是标准的JaveScripts语言的对象,可以被所有语言读取,也可以方便的存储到磁盘或者通过网络传输,json和python内置的数据类型对应如下:

json类型 python类型
{} dict
[] list
"String" str
1234.57 int或float
true/false True/False
null None
dic={'a':1}
res=json.dumps(dic)
print(res,type(res))   #{"a": 1} <class 'str'>

x=None
res=json.dumps(x)
print(res,type(res))   #null <class 'str'>

#序列化:json.dumps和json.dump用法
user = {"name":'lary','age':18}
with open('user.json','w',encoding='utf-8') as f:
    f.write(json.dumps(user))           #json.dumps把单引号变为双引号

user = {"name": 'lary', 'age': 16}
json.dump(user,open('user.json','w',encoding='utf-8'))

#反序列化:json.loads和json.load的用法
with open('user.json','r',encoding='utf-8') as f:
    data=json.loads(f.read())
    print(data)

data=json.load(open('user.json','r',encoding='utf-8'))
print(data)

  序列化之pickle

   pickle只能用于python,可以识别python所有的数据类型,但是可能不同版本的python彼此都不兼容

#序列化:pickle.dumps和pickle.dump,序列化后的数据类型为bytes类型
s={1,2,3,4,5}

with open('user.pkl','wb',) as f:
    f.write(pickle.dumps(s))

pickle.dump(s, open('user.pkl', 'wb'))

#反序列化:pickle.loads和pickle.load
with open('user.pkl','rb') as f:
    data=pickle.loads(f.read())
    print(data)

data=pickle.load(open('user.pkl','rb'))
print(data)

shelve模块

import shelve

   shelve模块比pickle模块简单,只有一个open函数,返回类似字典的对象,可读可写;key必须为字符串,而值可以是python所支持的数据类型

f=shelve.open('db.sh1')
#存数据
f['student1']={'name':'lary',"age":18}
#取数据
print(f['student1'])
f.close()

xml模块

  xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>
xml数据

  xml协议在各个语言里的都 是支持的,在python中可以用以下模块操作xml

from xml.etree import ElementTree

tree=ElementTree.parse('a.xml')

root=tree.getroot()
print(root.tag,root.attrib,root.text)

#三种查找方式
#从子节点查找
print(root.find('country'))
print(root.findall('country'))
#从树形结构中查找
print(list(root.iter('rank')))

for country in root.findall('country'):
    rank=country.find('rank')
    print(rank.tag,rank.attrib,rank.text)

#遍历文档树
for item in root:
    #print('=====>',item.attrib['name'])
    for i in item:
        print(i.tag,i.attrib,i.text)

#修改文档
for year in root.iter('year'):
    #print(year.tag,year.attrib,year.text)
    year.set('updated','yes')
    year.text=str(int(year.text)+1)

tree.write('a.xml')

#添加节点
for country in root:
    obj=ElementTree.Element('egon')
    obj.attrib={"name":'egon',"age":'18'}
    obj.text='egon is good'
    country.append(obj)
View Code

configparser模块

[section1]
k1 = v1
k2:v2
user=egon
age=18
is_admin=true
salary=31

[section2]
k1 = v1
ConfigureFile

  在python中可以用以下模块操作xml

import configparser

config=configparser.ConfigParser()
config.read('my.ini')

#查看
#查看所有的标题
res=config.sections()
print(res)

#查看标题section下所有key=value的key
options=config.options('section1')
print(options)

#查看标题section下所有key=value的(key,value)形式
item=config.items('section1')
print(item)

#查看标题section1下user的值=>字符串格式
val=config.get('section1','user')
print(val)

#查看标题section1下age的值=>整数格式
val1=config.getint('section1','age')
print(val1)

#查看标题section1下is_admin的值=>布尔值格式
val2=config.getboolean('section1','is_admin')
print(val2)

#查看标题section1下salary的值=>浮点型格式
val3=config.getfloat('section1','salary')
print(val3)

#修改
#删除整个标题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('lary')

#在标题egon下添加name=lary,age=18的配置
config.set('lary','name','lary')
config.set('lary','age','18') #必须是字符串

#最后将修改的内容写入文件,完成最终的修改
config.write(open('a.cfg','w'))
View Code

hashlib模块

  hash:一种算法,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法。特点是内容相同则hash运算结果相同,内容稍微改变则hash值则变;不可逆推;无论校验多长的数据,得到的哈希值长度固定

import hashlib

m=hashlib.md5()

m.update('lary123'.encode('utf-8'))
print(m.hexdigest())

#对加密算法中添加自定义key再来做加密
hash=hashlib.sha256('898sadfd'.encode('utf-8'))
hash.update('hello'.encode('utf-8'))
print(hash.hexdigest())

#hmac模块,它内部对我们创建key和内容进行进一步的处理然后再加密
import hmac

h=hmac.new('good'.encode('utf-8'))
h.update('hello'.encode('utf-8'))
print(h.hexdigest())
#模拟撞库破解密码
pwd={
    "lary",
    "lary123",
    "lary321"
}
def make_pwd_dic(pwd):
    dic={}
    for p in pwd:
        m=hashlib.md5()
        m.update(p.encode('utf-8'))
        dic[p]=m.hexdigest()
    return dic

def break_code(code,pwd_dic):
    for k,v in pwd_dic.items():
        if v==code:
            print("密码是%s"%k)

code='3043b3256c1c64338167b7b1d71d0c14'
break_code(code,make_pwd_dic(pwd))
撞库模拟

subprocess模块

import subprocess
import time

subprocess.Popen('tasklist',shell=True)
print('===主')
time.sleep(1)

obj1=subprocess.Popen('tasklist',shell=True,
                 stdout=subprocess.PIPE,
                 stderr=subprocess.PIPE,
                 )

obj2=subprocess.Popen('findstr python',shell=True,
                 stdin=obj1.stdout,
                 stdout=subprocess.PIPE,
                 stderr=subprocess.PIPE
                 )

print(obj2.stdout.read().decode('gbk'))

相关推荐