第二十 二天 PYTHON学习

【今日学习】

logging模块(掌握)

1.日志级别

CRITICAL = 50 
ERROR = 40
WARNING = 30 
INFO = 20
DEBUG = 10
NOTSET = 0

'''
import logging

logging.basicConfig(
filename='access.log',
filemode='a', format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',level=40)# 指定日志格式
logging.debug('debug....')#10
logging.info('info....')#20
logging.warning('warning....')#30
logging.error('error....')#40
logging.critical('crtical....')#50
'''

结果

2018-10-18 21:13:47 PM - root - ERROR -logging模块使用:  error....
2018-10-18 21:13:47 PM - root - CRITICAL -logging模块使用: crtical....

2.logging模块的四类对象
logging模块的Formatter,Handler,Logger,Filter对象

#logger:产生日志的对象

logger1=logging.getlogger('xxx')

#Filter:过滤日志的对象

(不常用)

#Handler:接收日志然后控制打印到不同的地方,FileHandler用来打印到文件中,StreamHandler用来打印到终端

fh1=logging.FileHadler('filename='a1.log',encoding='utf-8')
fh1=logging.FileHadler('filename='a1.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',)
formatter2=logging.Formatter(fmt='%(asctime)s - %(name)s', datefmt='%Y-%m-%d %H:%M:%S %p',)

#为logger对象绑定handler
logger1.addhandler(fh1)
logger1.addhandler(fh2)
logger1.addhandler(sh)

# 为handler对象绑定日志格式
fh1.setFormatter(formatter1)
fh2.setFormatter(formatter2)
sh.setFormatter(formatter2)

#设置日志级别
logger1.setLevel(10)
fh1.setLevel(20)
fh2.setLevel(20)
sh.setLevel(20)

logger1.debug('调试信息')
 
# """
# logging配置
#为日志模块配置日志输出格式,输出途径
# """
#
# 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配置文件
 re模块
# re
# ===========匹配模式==============
# 先分析规律,再写正则表达式
import re
print(re.findall('\w','ab 12\+- *&_'))#['a', 'b', '1', '2', '_']字母数字下划线
print(re.findall('\W','ab 12\+- *&_'))#[' ', '\\', '+', '-', ' ', '*', '&']非字母数字下划线
print(re.findall('\s','ab 1\r\n2\t\+- *&_'))#[' ', '\r', '\n', '\t', ' '] 空白字符
print(re.findall('\S','ab 1\r\n2\t\+- *&_'))#['a', 'b', '1', '2', '\\', '+', '-', '*', '&', '_']非空白字符
print(re.findall('\d','ab 1\r\n2\t\+- *&_'))#['1', '2']只匹配数字
print(re.findall('\D','ab 1\r\n2\t\+- *&_'))#['a', 'b', ' ', '\r', '\n', '\t', '\\', '+', '-', ' ', '*', '&', '_']非数字


print(re.findall('\w_sb','egon alex_sb123123wxx_sb,lxx_sb'))#['x_sb', 'x_sb', 'x_sb']
print(re.findall('run','run is nb run'))#['run','run']
print(re.findall('\Arun','run is nb run'))#['run'] 只找开头,如果开头没有就不用往后匹配了,以后很少用,常用' ^ ' 上尖号
print(re.findall('^run','run is nb run'))#['run']只找开头,如果开头没有就不用往后匹配了,常用
print(re.findall('run\Z','run is nb run'))#['run']只找末尾,如果末尾没有就不用往前匹配了,不常用,常用$符号
print(re.findall('run$','run is nb run'))#['run']只找末尾,如果末尾没有就不用往前匹配了,常用
print(re.findall('^run$','run'))#正着找,倒着找都是它
print(re.findall('^run$','run1'))#[]找不到

# ===========重复匹配==============
# . ? * + {m,n} .* .*?
# 1、 .:代表除了换行符外的任意一个字符
print(re.findall('a.c','abc a1c aAc aaaaac'))#['abc', 'a1c', 'aAc', 'aac'] 没法匹配换行符在a与c的字符,比如'a\nc'
print(re.findall('a.c','abc a1c aAc aaaa\nc',re.DOTALL))# 加上后面可以匹配所有字符,包括换行符
#2. ?代表?左边那一个字符出现0次或一次,没有就不要,有就要一个
print(re.findall('ab?','a ab abb abbb abbbb abbbb'))#['a', 'ab', 'ab', 'ab', 'ab', 'ab'],有就要一个b,没有就不要
# ab?
#3. *:代表*左边那个字符出现0次或无穷次,没有对上就结束
print(re.findall('ab*','a ab abb abbb abbbb abbbb a1bbbbb'))#['a', 'ab', 'abb', 'abbb', 'abbbb', 'abbbb', 'a']
# ab* 没有对上,*号,左边的b出现0次,取出小a
#4.+:代表+号左边那个字符至少出现1次或无穷次
print(re.findall('ab+','a ab abb abbb abbbb abbbb a1bbbbb'))#['ab', 'abb', 'abbb', 'abbbb', 'abbbb']

#5.{m,n}:代表{m,n}符号左边那一个字符出现m次到n次
print(re.findall('ab?','a ab abb abbb abbbb abbbb'))#['a', 'ab', 'ab', 'ab', 'ab', 'ab']
print(re.findall('ab{0,1}','a ab abb abbb abbbb abbbb'))#['a', 'ab', 'ab', 'ab', 'ab', 'ab']
# 与问号的结果一样
print(re.findall('ab*','a ab abb abbb abbbb abbbb a1bbbbb'))
print(re.findall('ab{0,}','a ab abb abbb abbbb abbbb a1bbbbb'))
# 与*号的结果一样

print(re.findall('ab+','a ab abb abbb abbbb abbbb a1bbbbb'))
print(re.findall('ab{1,}','a ab abb abbb abbbb abbbb a1bbbbb'))
# 与加号的结果一样

# 还有以上符号不具备的功能
print(re.findall('ab{1,3}','a ab abb abbb abbbb abbbb a1bbbbb'))#['ab', 'abb', 'abbb', 'abbb', 'abbb'],有就往大了取,没有就有多少取多少,至少取一个

# 6、 .*:匹配任意长度,任意的字符====》贪婪匹配
print(re.findall('a.*c','ac a123c aaaaaac a *123)()c asdfasdwfwf'))#['ac a123c aaaaaac a *123)()c']

#7、 .*?:匹配任意长度,任意的字符====》非贪婪匹配,推荐使用
print(re.findall('a.*?c','awdscfdc'))#['awdsc'] 找到一个符合条件的就不再往后匹配了

#8、(): 分组,只将括号内匹配的内容拿出来,其余的匹配不要/()既有分组的作用,也有把括号内的内容当成整体去匹配的作用,
# ?: 可以破除只把括号内匹配的内容拿出来,可以把括号外匹配的内容也拿出来
print (re.findall('alex_sb','alex_sb asfefffwfralex_sb'))#['alex_sb', 'alex_sb']
print (re.findall('(alex)_sb','alex_sb asfefffwfralex_sb'))# ['alex', 'alex']加括号不影响原来匹配规则的,但只留括号内需要匹配的内容

print(re.findall('https://"(.*?)"','https://"www.cnblogs.com"/runjam/"'))#['www.cnblogs.com']
# https://"(.*?)" 取到第一个符合要求就结束

print(re.findall('(?:ab)+123','ababab123')) #findall的结果不是匹配的全部内容,而是组内的内容,?:可以让结果为匹配的全部内容
print(re.findall('(ab)+123','ababab123')) #['ab'],匹配到末尾的ab123中的ab
print(re.findall('(?:ab)+123','abbab1234'))#['ab123']
print(re.findall('(ab)+123','abbb123'))#[]
print(re.search('ab+123','aaa123'))#None
print(re.findall('ab+123','abbb123'))#['abbb123']
print(re.findall('(abab)+123','ababab123'))#['abab']
print(re.search('(ab)+123','abab123').group())#abab123
print(re.search('ab+123','abab123').group())#ab123

print(re.findall('compan(?:y|ies)','Too many companies have gone bankrupt, and the next one is my company'))

# 9、[ ]: 匹配一个指定范围内的字符(这一个字符来自于括号内定义的)
print( re.findall('a.c','a1c a+c a2c a-c acc aAc'))#['a1c', 'a+c', 'a2c', 'a-c', 'acc', 'aAc']取出一个字符,除了换行符
print( re.findall('a[1-9]c','a1c a+c a2c a-c acc aAc'))#['a1c', 'a2c']取出a与c之间字符是1到9的数字,注意横杆在中间表示从哪到哪的意思
print( re.findall('a[^1-9]c','a1c a+c a2c a-c acc aAc'))#['a+c', 'a-c', 'acc', 'aAc']上尖号^ 在中括号内表示 取反的意思,中间字符除了1-9都取

print(re.findall('[a-z]_sb','egon alex_sb123123wxx_sb,lxx_sb'))#['x_sb', 'x_sb', 'x_sb']
print(re.findall('[a-z]+_sb','egon alex_sb123123wxx_sb,lxx_sb'))#['alex_sb', 'wxx_sb', 'lxx_sb']
print(re.findall('[a-z]+_sb','egon alex_sbefefefwxx_sb,lxx_sb'))#['alex_sb', 'efefefwxx_sb', 'lxx_sb']


#10、 | :或者
print(re.findall('compan(y|ies)','Too many companies have gone bankrupt, and the next one is my company'))#['ies', 'y']
print(re.findall('compan(?:y|ies)','Too many companies have gone bankrupt, and the next one is my company'))#['companies', 'company']


# ===========================re模块提供的方法介绍===========================

# 1.re.search()
print(re.findall('run','1215333run sadwfwf run'))#['run', 'run']
print(re.search('run','1215333run sadwfwf run').group())#run 意思是只找一个就结束
print(re.search('^run','run sadwfwf run').group())#run 意思也是从头开始找,如果开头找不到,就不再往后找了
# 2.re.match()
print(re.match('run','run sadwfwf run').group())#run, match是从字符串开头匹配,如果开头匹配不上,那就不到了,并且报错

# 3.re.split()
info='a:b:c:d'
print(info.split(':'))#split里面只能放字符,不能放正则表达式,拆分必须以同样的字符分割才能实现
info=r'a :b\c/d'
print(re.split('[ :\\\/]',info))#['a', '', 'b', 'c', 'd']
# 4.re.sub()

print(re.sub('run','RUN','run is huaband run'))#RUN is huaband RUN
print(re.sub('^run','RUN','run is huaband run'))#RUN is huaband run ,换第一个run
print(re.sub('(.*?)(run)(.*?)(run)(.*?)',r'\1\2\3RUN\5','123run is huaband run223'))#123run is huaband RUN223, 换第二个run
print(re.sub('(.*?)(run)(.*?)(run)(.*?)',r'\2\1\3RUN\5','123run is huaband run223'))#run123 is huaband RUN223,1的位置与2的位置进行调换


hashlib模块

 

# 1、什么叫hash:hash是一种算法(3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法),该算法接受传入的内容,经过运算得到一串hash值
# 2、hash值的特点是:
#2.1 只要传入的内容一样,得到的hash值必然一样=====>要用明文传输密码文件完整性校验
#2.2 不能由hash值返解成内容=======》把密码做成hash值,不应该在网络传输明文密码
#2.3 只要使用的hash算法不变,无论校验的内容有多大,得到的hash值长度是固定的

 hash算法就像一座工厂,工厂接收你送来的原材料(可以用m.update()为工厂运送原材料),经过加工返回的产品就是hash值

得到hash值得语法

 import hashlib

m=hashlib.md5()
 m.update('hello'.encode('utf8'))
print(m.hexdigest())#hash值:5d41402abc4b2a76b9719d911017c592

    以上加密算法虽然依然非常厉害,但时候存在缺陷,即:通过撞库可以反解。所以,有必要对加密算法中添加自定义key再来做加密。


import hashlib

# ######## 256 ########

hash = hashlib.sha256('898oaFs09f'.encode('utf8'))#加盐
hash.update('alvin'.encode('utf8'))
print (hash.hexdigest())#e79e68f070cdedcfe63eaf1a2e92c83b4cfb1b5c6bc452d214c1b7e77cdfd1c7

 

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

1 import hmac
2 h = hmac.new('alvin'.encode('utf8'))
3 h.update('hello'.encode('utf8'))
4 print (h.hexdigest())#320df9832eab4c038b6c1d7ed73a5940

#要想保证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
'''

suprocess模块

 #windows下:
 # dir | findstr 'test*'
 # dir | findstr 'txt$'
 import subprocess
 res1=subprocess.Popen(r'dir C:\Users\Administrator\PycharmProjects\test\函数备课',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解码
 




 

                                                      

 

 
posted @ 2018-10-23 14:46  runjam  阅读(118)  评论(0编辑  收藏  举报