Logging模块
'''
critical=50
error=40
warning=30
info=20
debug=10
notset=0
'''
# import logging #默认的日志级别是:warning,默认的输出目标是:终端
#
#
# logging.debug('debug')
# logging.info('info')
# logging.warning('warn123')
# logging.error('error')
# logging.critical('critical')
#控制日志打印到文件中,并且自己定制日志的输出格式
# import logging
#
# logging.basicConfig(
# filename='access.log',
# # filemode='w', #默认是a模式
# format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
# datefmt='%Y-%m-%d %H:%M:%S %p',
# level=10,
# )
#
#
# logging.debug('debug')
# logging.info('info')
# logging.warning('warn123')
# logging.error('error')
# logging.critical('critical')
#待解决的问题:
#1:既往终端打印,又往文件中打印
#2:控制输出到不同的目标(终端+文件)的日志,有各自的配置信息
import logging
#一:Logger对象:负责产生日志信息
logger=logging.getLogger('root')
#二:Filter对象:略
#三:Handler对象:负责接收Logger对象传来的日志内容,控制打印到终端or文件
h1=logging.FileHandler('t1.log')
h2=logging.FileHandler('t2.log')
h3=logging.StreamHandler()
#四:formmater对象
#给文件
formatter1=logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',
)
#给终端
formatter2=logging.Formatter(
'%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',
)
#五:为handler对象绑定日志格式,设置日志级别
#给文件:绑定到Filehandler对象
h1.setFormatter(formatter1)
h2.setFormatter(formatter1)
#给终端:绑定到Streamhandler对象
h3.setFormatter(formatter2)
#设置日志级别
h1.setLevel(30)
h2.setLevel(30)
h3.setLevel(30)
#六:把h1,h2,h3都add给logger,这样logger对象才能把自己的日志交给他们三负责输出
logger.addHandler(h1)
logger.addHandler(h2)
logger.addHandler(h3)
logger.setLevel(20) #括号的数字一定要<=Hanlder对象的数字
#七:测试
# logger.debug('debug')
# logger.info('info')
# logger.warning('warn123') #30
# logger.error('error')
# logger.critical('critical')
#强调:如果想要日志成功打印
# 日内容的级别 >= Logger对象的日志级别 >= Handler对象的日志级别
#了解知识点:Logger对象的继承
import logging
logger1=logging.getLogger('a')
logger2=logging.getLogger('a.b')
logger3=logging.getLogger('a.b.c')
h3=logging.StreamHandler()
formatter2=logging.Formatter(
'%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',
)
h3.setFormatter(formatter2)
h3.setLevel(10)
logger1.addHandler(h3)
logger1.setLevel(10)
logger2.addHandler(h3)
logger2.setLevel(10)
logger3.addHandler(h3)
logger3.setLevel(10)
# logger1.debug('logger1 debug')
# logger2.debug('logger2 debug')
logger3.debug('logger2 debug')
Re模块
import re
# print(re.findall('alex','12a3 alex say hello alex sb 123 _ 4%5*6'))
# # alex
# print(re.findall('aaa','12a1aaa'))
# # aba
# print(re.findall('w','alex say alex sb 123 _ 4%5*'))
# print(re.findall('W','alex say alex sb 123 _ 4%5*'))
# print(re.findall('s','al e
x hello alex sb 123 _ 4%5*'))
# print(re.findall('S','al e
x hello alex sb 123 _ 4%5*'))
# print(re.findall('d','al e
x hello alex sb 123 _ 4%5*'))
# # print(re.findall('dd','al e
x hel12345lo alex sb 123 _ 4%5*'))
# print(re.findall('D','al e
x hello alex sb 123 _ 4%5*'))
# print(re.findall('Al','alex say hello'))
# print(re.findall('llo','alex say hello'))
# print(re.findall('^l','alex say hello'))
# print(re.findall('llo$','alex say hello'))
#
#
# print(re.findall('
','al e
x hello alex sb 123 _ 4%5*'))
# print(re.findall(' ','al e
x hello alex sb 123 _ 4%5*'))
#重复匹配:. [] ? * + {}
# print(re.findall('a.c','a1c a%c abc accc acccc'))
# print(re.findall('a.c','a1c a%c a
c accc acccc',re.S))
# print(re.findall('a.c','a1c a%c a
c accc acccc',re.S))
# print(re.findall('a[0-9]c','a1c a%c a
c accc acccc',re.S))
# print(re.findall('a[a-z]c','a1c a%c a
c accc acccc',re.S))
# print(re.findall('a[A-Z]c','a1c a%c a
c accc acccc aAc aAAc',re.S))
# print(re.findall('a[0-9a-zA-Z]c','a1c a%c a
c accc acccc aAc aAAc',re.S))
# print(re.findall('a[% ]c','a c a1c a%c a+c a-c a/c a*c',re.S))
# print(re.findall('a[^% ]c','a c a1c a%c a+c a-c a/c a*c',re.S))
# print(re.findall('a[+-*/]c','a c a1c a%c a+c a-c a/c a*c',re.S))
# print(re.findall('a[-+*/]c','a c a1c a%c a+c a-c a/c a*c',re.S))
# print(re.findall('a[+*/-]c','a c a1c a%c a+c a-c a/c a*c',re.S))
# print(re.findall('a.*?c','a c a1c a%c a+c a-c a/c a*c',re.S))
#?:左边那个字符出现0次或1次
# print(re.findall('ab?','a ab abb abbb abbbbbb'))
# print(re.findall('ab{0,1}','a ab abb abbb abbbbbb'))
#*:左边那个字符出现0次或无穷次
# print(re.findall('ab*','a ab abb abbb abbbbbb abbc123bbbb'))
# print(re.findall('ab{0,}','a ab abb abbb abbbbbb abbc123bbbb'))
#+:左边那个字符出现1次或无穷次
# print(re.findall('ab+','a ab abb abbb abbbbbb abbc123bbbb'))
# print(re.findall('ab{1,}','a ab abb abbb abbbbbb abbc123bbbb'))
#{n,m}:左边那个字符出现n到m次
# print(re.findall('ab{3}','a ab abb abbb abbbbbb abbc123bbbb'))
# print(re.findall('ab{3,}','a ab abb abbb abbbbbb abbc123bbbb'))
# print(re.findall('ab{0,1}','a ab abb abbb abbbbbb abbc123bbbb'))
# print(re.findall('ab{0,}','a ab abb abbb abbbbbb abbc123bbbb'))
# print(re.findall('ab{1,}','a ab abb abbb abbbbbb abbc123bbbb'))
#贪婪匹配:.*
# print(re.findall('a.*b','a123b456b'))
#非贪婪匹配:.*?
# print(re.findall('a.*?b','a123b456b'))
#分组:()
# print(re.findall('<imag href="(.*)" />',
# '<h1>hello</h1><a href="http://www.baidu.com"></a><imag href="http://www.baidu.com/a.jpg" />'))
#
#
#
# print(re.findall('<imag href="(?:.*)" />',
# '<h1>hello</h1><a href="http://www.baidu.com"></a><imag href="http://www.baidu.com/a.jpg" />'))
#|
# print(re.findall('compan(?:ies|y)','Too many companies have gone bankrupt, and the next one is my company'))
# print(re.findall('a\\c','ac a12 a2c')) #'a\c'
# print(re.findall(r'a\c','ac a12 a2c')) #'a\c'
# print(re.findall('alex','alex say hello alex'))
#与findall用法完全一致,不一样的地方在于search匹配一次就结束
# print(re.search('alex','alex say hello alex').group())
#match代表从头匹配
# print(re.match('alex','alex say hello alex').group())
# print(re.search('^alex','alex say hello alex').group())
# re.split()
# print(re.split(':','root:x:0:0:/root::/bin/bash'))
# re.sub()
# print(re.sub('alex','SB','alex say i have on telsa my name is alex',1))
# print(re.subn('alex','SB','alex say i have on telsa my name is alex'))
# print(re.sub(r'(w+)(W+)(w+)(W+)(w+)',r'52341','alex-love: SB'))
# print(re.sub(r'^al',r'AAAAAAAAA','alex-love: SB alex'))
# re.compile()
# print(re.findall('^alex','alex say hello alex'))
# print(re.search('^alex','alex say hello alex'))
# obj=re.compile(r'^alex')
# print(obj.findall('alex say hello alex'))
# print(obj.search('alex say hello alex').group())
#补充:
# print(re.findall(r'<.*?>.*?</.*?>','<h1>hello</h1>'))
# print(re.findall(r'<(.*?)>.*?</(.*?)>','<h1>hello</h1>'))
# print(re.findall(r'<(.*?)>.*?</(1)>','<h1>hello</h1>'))
# print(re.findall(r'<(?P<k>.*?)>.*?</(?P=k)>','<h1>hello</h1>'))
# print(re.findall('-?d+.?d*',"1-12*(60+(-40.35/5)-(-4*3))"))
# print(re.findall('-?d+',"1-12*(60+(-40.35/5)-(-4*3))"))
# print(re.findall('-?d+.d+',"1-12*(60+(-40.35/5)-(-4*3))"))
# print(re.findall('-?d+.d+|(-?d+)',"1-12*(60+(-40.35/5)-(-4*3))"))
# print(re.findall('(-?d+.d+)|-?d+',"1-12*(60+(-40.35/5)-(-4*3))"))
expression='1-2*((60+2*(-3-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'
print(re.search(r'(([-+*/]?d+.?d*)+)',expression).group())
# print(eval(expression))
Time模块
#time与datetime
import time
#时间戳
# print(time.time())
#结构化的实际
# print(time.localtime())
# print(time.localtime().tm_year)
# print(time.gmtime())
#格式化的字符串
# print(time.strftime('%Y-%m-%d %H:%M:%S'))
# print(time.strftime('%Y-%m-%d %X'))
print(time.asctime(time.localtime()))
print(time.ctime(time.time()))
#了解
# print(time.localtime(123123123))
# print(time.gmtime(123123123))
# print(time.mktime(time.localtime()))
# print(time.strptime('2017:03-01','%Y:%m-%d'))
# print(time.strftime('%Y-%m-%d %X',time.gmtime()))
import datetime
# print(datetime.datetime.now())
# print(datetime.datetime.now()+datetime.timedelta(days=3))
# print(datetime.datetime.now()-datetime.timedelta(days=3))
# print(datetime.datetime.now()+datetime.timedelta(days=-3))
# print(datetime.datetime.now()+datetime.timedelta(hours=3))
# print(datetime.datetime.now()+datetime.timedelta(minutes=3))
# print(datetime.datetime.fromtimestamp(123123123))
# print(datetime.datetime.now().replace(hour=22))
Random模块
import random
# print(random.choice([1,2,'a',[3,4]]))
# print(random.sample([1,2,'a','b','c'],2))
# print(random.uniform(1,3))
# item=[1,3,5,7,9]
# random.shuffle(item)
# print(item)
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
print(make_code(10))
Os模块
import os
#
# res=os.system('tasklist')
# print('==========================?>',res)
# print(os.path.split(r'acd.txt') )
# print(os.path.dirname(r'acd.txt') )
# print(os.path.basename(r'acd.txt') )
# print(os.stat(r'C:UsersAdministratorPycharmProjects19期day6softconfsettings.py').st_size)
# print(os.path.getsize(r'C:UsersAdministratorPycharmProjects19期day6softconfsettings.py'))
# print(os.path.normcase('c:/Windows\system32\'))
print(os.path.normpath('c://windows\System32\../Temp/') )
x=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(x)
print(os.path.normpath(os.path.join(
os.path.abspath(__file__),
'..',
'..'
)
))
Sys模块
import sys
#sys.path
# print(sys.argv[1])
# print(sys.argv[2])
#sys.exit(3)
# print('[%-10s]' %'#')
# print('[%-10s]' %'##')
# print('[%-10s]' %'###')
# print('[%-10s]' %'####')
# print('[%-10s]' %'#####')
# print('%d%%' %30)
# print(('[%%-%ds]' %50) %'#')
import time
def progress(percent,width=50):
if percent > 1:
percent=1
show_str=('[%%-%ds]' %width) %(int(percent*width)*'#')
print('
%s %s%%' %(show_str,int(percent*100)),end='',file=sys.stdout,flush=True)
total_size=10212
recv_size=0
while recv_size < total_size:
time.sleep(0.2) #1024
recv_size+=1024
percent=recv_size/total_size
progress(percent,width=30)
Shutil模块
# import shutil
#打包压缩:day5_bak.tar.gz
# shutil.make_archive('day5_bak','gztar',root_dir=r'C:UsersAdministratorPycharmProjects19期day5')
import tarfile
obj=tarfile.open('day5_bak.tar.gz')
obj.extractall('aaa')
obj.close()
Configparser模块
# import configparser
# obj=configparser.ConfigParser()
# obj.read('my.cnf')
# print(obj.sections())
# print(obj.options('mysql'))
# print(obj.items('mysql'))
# print(obj.get('mysql','user')) #拿到的结果是字符串类型
# x=obj.get('mysqld','port')
# print(x,type(x))
#
# print(type(obj.getint('mysqld','port')))
# print(type(obj.getboolean('mysqld','x')))
# print(type(obj.getfloat('mysqld','y')))
#判断是否存在
import configparser
obj=configparser.ConfigParser()
obj.read('my.cnf')
print(obj.has_section('mysql'))
print(obj.has_option('alex','is_sbxxxxxxxxxxx'))
#了解:修改操作
# import configparser
# obj=configparser.ConfigParser()
# obj.read('my.cnf')
#
# obj.add_section('alex')
# obj.set('alex','password','123')
# obj.set('alex','is_sb','True')
# obj.remove_section('mysqld')
#
# obj.remove_option('mysql','user')
#
# obj.write(open('my.cnf','w'))
Hashlib模块
import hashlib
# m=hashlib.md5()
#
# m.update('hello'.encode('utf-8'))
# m.update('world'.encode('utf-8'))
# print(m.hexdigest()) #fc5e038d38a57032085441e7fe7010b0
# m=hashlib.md5()
# m.update('helloworld'.encode('utf-8'))
# print(m.hexdigest()) #fc5e038d38a57032085441e7fe7010b0
# with open(r'C:UsersAdministratorPycharmProjects19期day67_sys模块.py','rb') as f:
# m=hashlib.md5()
# m.update(f.read())
# print(m.hexdigest()) #267214cb9601ca23ebd9dd604b74a20f
# with open(r'C:UsersAdministratorPycharmProjects19期day67_sys模块.py','rb') as f:
# m=hashlib.md5()
# for line in f:
# m.update(line)
# print(m.hexdigest()) #267214cb9601ca23ebd9dd604b74a20f
# s='alex3714'
#
# m=hashlib.md5()
# m.update(s.encode('utf-8'))
# s_hash=m.hexdigest()
#
# print(s_hash)
#
#
# passwds=[
# 'alex3714',
# '123456',
# 'alex123',
# '123alex',
# 'Alex@3012'
# ]
#
# def make_dic(passwds):
# dic={}
# for passwd in passwds:
# m=hashlib.md5()
# m.update(passwd.encode('utf-8'))
# dic[passwd]=m.hexdigest()
#
# return dic
#
#
#
# def break_code(s1,dic):
# for p in dic:
# if s1 == dic[p]:
# return p
#
#
# s1='aee949757a2e698417463d47acac93df'
#
# dic=make_dic(passwds)
# res=break_code(s1,dic)
#
# print(res)
#
#密码加盐
# import hashlib
#
#
# # m=hashlib.md5('天王盖地虎'.encode('utf-8'))
# m=hashlib.sha512('天王盖地虎'.encode('utf-8'))
# m.update('alex3714'.encode('utf-8'))
# m.update('宝塔镇河妖'.encode('utf-8'))
# print(m.hexdigest()) #b74c5a073f1faf83dbc7b3c30a10ef4d
#
import hmac
#要想保证俩次校验的结果是一样的,处理内容必须以外,key必须一样
m1=hmac.new('哈了个哈'.encode('utf-8'))
m1.update('alex3714'.encode('utf-8'))
print(m1.hexdigest())
# m2 = hmac.new('哈'.encode('utf-8'))
# m2.update('了个哈alex3714'.encode('utf-8'))
# print(m2.hexdigest())
m3 = hmac.new('哈了个哈'.encode('utf-8'))
m3.update('alex'.encode('utf-8'))
m3.update('3714'.encode('utf-8'))
print(m3.hexdigest())
作业
基于递归和正则表达式实现的计算器,源码如下:
#!/usr/bin/env python
# Author:hongjie.gao
import re,os,sys
def compute_exponent(arg):
""" 操作指数
:param expression:表达式
:return:计算结果
"""
val = arg[0]
pattern = re.compile(r'd+.?d*[*]{2}[+-]?d+.?d*')
mch = pattern.search(val)
if not mch:
return
content = pattern.search(val).group()
if len(content.split('**'))>1:
n1, n2 = content.split('**')
value = float(n1) ** float(n2)
else:
pass
before, after = pattern.split(val, 1)
new_str = "%s%s%s" % (before,value,after)
arg[0] = new_str
compute_exponent(arg)
def compute_mul_div(arg):
""" 操作乘除
:param expression:表达式
:return:计算结果
"""
val = arg[0]
pattern = re.compile(r'd+.?d*[*/\%//]+[+-]?d+.*d*')
mch = pattern.search(val)
if not mch:
return
content = pattern.search(val).group()
if len(content.split('*'))>1:
n1, n2 = content.split('*')
value = float(n1) * float(n2)
elif len(content.split('//'))>1:
n1, n2 = content.split('//')
value = float(n1) // float(n2)
elif len(content.split('%'))>1:
n1, n2 = content.split('%')
value = float(n1) % float(n2)
elif len(content.split('/'))>1:
n1, n2 = content.split('/')
value = float(n1) / float(n2)
else:
pass
before, after = pattern.split(val, 1)
new_str = "%s%s%s" % (before,value,after)
arg[0] = new_str
compute_mul_div(arg)
def compute_add_sub(arg):
""" 操作加减
:param expression:表达式
:return:计算结果
"""
while True:
if arg[0].__contains__('+-') or arg[0].__contains__("++") or arg[0].__contains__('-+') or arg[0].__contains__("--"):
arg[0] = arg[0].replace('+-','-')
arg[0] = arg[0].replace('++','+')
arg[0] = arg[0].replace('-+','-')
arg[0] = arg[0].replace('--','+')
else:
break
if arg[0].startswith('-'):
arg[1] += 1
arg[0] = arg[0].replace('-','&')
arg[0] = arg[0].replace('+','-')
arg[0] = arg[0].replace('&','+')
arg[0] = arg[0][1:]
val = arg[0]
pattern = re.compile(r'd+.?d*[+-]{1}d+.?d*')
mch = pattern.search(val)
if not mch:
return
content = pattern.search(val).group()
if len(content.split('+'))>1:
n1, n2 = content.split('+')
value = float(n1) + float(n2)
else:
n1, n2 = content.split('-')
value = float(n1) - float(n2)
before, after = pattern.split(val, 1)
new_str = "%s%s%s" % (before,value,after)
arg[0] = new_str
compute_add_sub(arg)
def compute(expression):
""" 操作加减乘除
:param expression:表达式
:return:计算结果
"""
inp = [expression,0]
# 处理表达式中的指数
compute_exponent(inp)
# 处理表达式中的乘除求余等
compute_mul_div(inp)
# 处理表达式的加减
compute_add_sub(inp)
if divmod(inp[1],2)[1] == 1:
result = float(inp[0])
result = result * -1
else:
result = float(inp[0])
return result
def exec_bracket(expression):
""" 递归处理括号,并计算
:param expression: 表达式
:return:最终计算结果
"""
pattern = re.compile(r'(([+-*/\%//**]*d+.*d*){2,})')
# 如果表达式中已经没有括号,则直接调用负责计算的函数,将表达式结果返回,如:2*1-82+444
#if not re.search('(([+-*/]*d+.*d*){2,})', expression):
if not pattern.search(expression):
final = compute(expression)
return final
# 获取 第一个 只含有 数字/小数 和 操作符 的括号
# 如:
# ['1-2*((60-30+(-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))']
# 找出:(-40.0/5)
content = pattern.search(expression).group()
# 分割表达式,即:
# 将['1-2*((60-30+(-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))']
# 分割更三部分:['1-2*((60-30+( (-40.0/5) *(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))']
before, nothing, after = pattern.split(expression, 1)
print('before:',expression)
content = content[1:len(content)-1]
# 计算,提取的表示 (-40.0/5),并活的结果,即:-40.0/5=-8.0
ret = compute(content)
print('%s=%s' %( content, ret))
# 将执行结果拼接,['1-2*((60-30+( -8.0 *(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))']
expression = "%s%s%s" %(before, ret, after)
print('after:',expression)
print("="*10,'previous result is',"="*10)
# 循环继续下次括号处理操作,本次携带者的是已被处理后的表达式,即:
# ['1-2*((60-30+ -8.0 *(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))']
# 如此周而复始的操作,直到表达式中不再含有括号
return exec_bracket(expression)
# 使用 __name__ 的目的:
# 只有执行 python index.py 时,以下代码才执行
# 如果其他人导入该模块,以下代码不执行
if __name__ == "__main__":
flag = True
os.system('clear') ###清屏###
print('
================================================================')
print('