logging模块介绍
import logging
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
)
logging.debug('debug') # 10
logging.info('info') # 20
logging.warning('warn') #30
logging.error('error') #40
logging.critical('critial') #50
日志模块的详细用法:
import logging
#1、Logger:产生日志
logger1=logging.getLogger('访问日志')
# logger2=logging.getLogger('错吴日志')
#2、Filter:几乎不用
#3、Handler:接收Logger传过来的日志,进行日志格式化,可以打印到终端,也可以打印到文件
sh=logging.StreamHandler() #打印到终端
fh1=logging.FileHandler('s1.log',encoding='utf-8')
fh2=logging.FileHandler('s2.log',encoding='utf-8')
#4、Formatter:日志格式
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 : %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',
)
formatter3=logging.Formatter(
fmt='%(asctime)s : %(module)s : %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',
)
#5、为handler绑定日志格式
sh.setFormatter(formatter1)
fh1.setFormatter(formatter2)
fh2.setFormatter(formatter3)
#6、为logger绑定handler
logger1.addHandler(sh)
logger1.addHandler(fh1)
logger1.addHandler(fh2)
#7、设置日志级别:logger对象的日志级别应该<=handler的日志界别
# logger1.setLevel(50)
logger1.setLevel(10) #
sh.setLevel(10)
fh1.setLevel(10)
fh2.setLevel(10)
#8、测试
logger1.debug('测试着玩')
logger1.info('运行还算正常')
logger1.warning('可能要有bug了')
logger1.error('不好了,真tm出bug了')
logger1.critical('完犊子,推倒重写')
日志的继承
import logging
#1、Logger:产生日志
logger1=logging.getLogger('root')
logger2=logging.getLogger('root.child1')
logger3=logging.getLogger('root.child1.child2')
#2、Filter:几乎不用
#3、Handler:接收Logger传过来的日志,进行日志格式化,可以打印到终端,也可以打印到文件
sh=logging.StreamHandler() #打印到终端
#4、Formatter:日志格式
formatter1=logging.Formatter(
fmt='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',
)
#5、为handler绑定日志格式
sh.setFormatter(formatter1)
#6、为logger绑定handler
logger1.addHandler(sh)
logger2.addHandler(sh)
logger3.addHandler(sh)
#7、设置日志级别:logger对象的日志级别应该<=handler的日志界别
# logger1.setLevel(50)
logger1.setLevel(10) #
logger2.setLevel(10) #
logger3.setLevel(10) #
sh.setLevel(10)
#8、测试
logger1.debug('爷爷')
logger2.debug('爸爸')
logger3.debug('孙子')
正则模块
import re
# print(re.findall('\w','egon 123 + _ - *'))
# print(re.findall('\W','egon 123 + _ - *'))
# print(re.findall('\s','ego\tn 12\n3 + _ - *'))
# print(re.findall('\S','ego\tn 12\n3 + _ - *'))
# print(re.findall('\d','ego\tn 12\n3 + _ - *'))
# print(re.findall('\D','ego\tn 12\n3 + _ - *'))
# print(re.findall('\n','ego\tn 12\n3 + _ - *'))
# print(re.findall('\t','ego\tn 12\n3 + _ - *'))
# print(re.findall('e','ego\tn 12\n3 +hello _ - *'))
# print(re.findall('^e','ego\tn 12\n3 +hello _ - *'))
# print(re.findall('o$','ego\tn 12\n3 +hello'))
#重复:.|?|*|+|{m,n}|.*|.*?
#.代表任意一个字符
# print(re.findall('a.b','a1b a b a-b aaaaaab'))
# a.b
# print(re.findall('a.b','a1b a b a\nb a-b aaaaaab',re.DOTALL))
# a.b
#?:代表?号左边的字符出现0次或者1
# print(re.findall('ab?','a ab abb abbbb a1b')) #['a','ab','ab','ab','a']
# # ab?
#*:代表*号左边的字符出现0次或者无穷次
# print(re.findall('ab*','a ab abb abbbb a1b')) #['a','ab','abb','abbbb','a']
# ab*
#+:代表+号左边的字符出现1次或者无穷次
# print(re.findall('ab+','a ab abb abbbb a1b')) #['ab','abb','abbbb']
# # ab+
# {m,n}:代表左边的字符出现m次到n次
# print(re.findall('ab{0,1}','a ab abb abbbb a1b')) #['ab','abb','abbbb']
# print(re.findall('ab?','a ab abb abbbb a1b')) #['ab','abb','abbbb']
# print(re.findall('ab{0,}','a ab abb abbbb a1b')) #['ab','abb','abbbb']
# print(re.findall('ab*','a ab abb abbbb a1b')) #['ab','abb','abbbb']
# print(re.findall('ab{1,}','a ab abb abbbb a1b')) #['ab','abb','abbbb']
# print(re.findall('ab+','a ab abb abbbb a1b')) #['ab','abb','abbbb']
# print(re.findall('ab{2,4}','a ab abb abbbb a1b')) #['abb', 'abbbb']
#.*:贪婪匹配
# print(re.findall('a.*b','xxxy123a123b456b'))
# a.*b
#.*?:非贪婪匹配
# print(re.findall('a.*?b','xxxy123a123b456b'))
#|:或者
# print(re.findall('compan(y|iess)','too many companiess have gone bankrupt, and the next one is my company'))
# print(re.findall('compan(?:y|iess)','too many companiess have gone bankrupt, and the next one is my company'))
# compan(y|iess)
# print(re.findall('href="(.*?)"','<a href="http://www.baidu.com">点击我</a>'))
#rawstring:
# print(re.findall(r'a\\c','a\c a1c aBc')) #a\\c->a\c
#[]:取中括号内任意的一个
# print(re.findall('a[a-z]b','axb azb aAb a1b a-b a+b'))
# print(re.findall('a[A-Z]b','axb azb aAb a1b a-b a+b'))
# print(re.findall('a[a-zA-Z]b','axb azb aAb a1b a-b a+b'))
# print(re.findall('a[0-9]b','axb azb aAb a1b a-b a+b'))
# print(re.findall('a[-+*/]b','axb azb aAb a1b a-b a+b'))
# print(re.findall('a[^-+*/]b','axb azb aAb a1b a-b a+b'))
#re模块的其他方法
#re.search :只匹配成功一次就返回
# print(re.search('a[*]b','axb azb aAb a1b a-b a+b'))
# print(re.search('a[0-9]b','axb azb aAb a1b a-b a2b a+b').group())
# re.match:从开头取
# print(re.match('a[0-9]b','axb azb aAb a1b a-b a2b a+b'))
# print(re.match('a[0-9]b','a1b axb azb aAb a1b a-b a2b a+b').group())
# print(re.search('^a[0-9]b','a1b axb azb aAb a1b a-b a2b a+b').group())
# re.split
# print(re.split(':','root:x:0:0::/root:/bin/bash',maxsplit=1))
# 'root:x:0:0::/root:/bin/bash'.split(':')
# re.sub
# print(re.sub('root','admin','root:x:0:0::/root:/bin/bash',1))
#了解
# print(re.sub('^([a-z]+)([^a-z]+)(.*?)([^a-z]+)([a-z]+)$',r'\5\2\3\4\1','root:x:0:0::/root:/bin/bash'))
# re.compile
obj=re.compile('a\d{2}b')
print(obj.findall('a12b a123b a12345b abbb'))
print(obj.search('a12b a123b a12345b abbb').group())
时间模块
import time
#掌握
print(time.time())
print(time.localtime())
print(time.localtime().tm_mday)
print(time.gmtime())
print(time.strftime('%Y-%m-%d %H:%M:%S'))
print(time.strftime('%Y-%m-%d %X'))
#了解
print(time.localtime(11111111))
print(time.localtime(time.time()))
print(time.gmtime(time.time()))
print(time.mktime(time.localtime()))
print(time.strftime('%Y-%m-%d',time.localtime()))
print(time.strptime('2017-03-01','%Y-%m-%d'))
print(time.asctime(time.localtime()))
print(time.ctime(111111))
#datetime
import datetime
print(datetime.datetime.now())
print(datetime.datetime.fromtimestamp(111111111))
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.now()+datetime.timedelta(seconds=3))
print(datetime.datetime.now().replace(year=1999,hour=12))
random模块
import random
print(random.random())
print(random.randint(1,3))
print(random.randrange(1,3))
print(random.choice([1,'alex','sb']))
print(random.sample([1,'alex','sb'],2))
print(random.uniform(1,4))
l=[1,3,4,2,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
print(make_code(7))
OS模块
import os
print(os.stat(r'F:\Python周末20期\day6\1 本节内容').st_size)
res=os.system('tasklist')
print('====>',res)
print(os.path.split(r'F:\Python周末20期\day6\1 本节内容'))
print(os.path.dirname(r'F:\Python周末20期\day6\1 本节内容'))
print(os.path.basename(r'F:\Python周末20期\day6\1 本节内容'))
print(os.path.isabs(r'C:\\a123sz'))
print(os.path.isabs(r'/root/a123sz'))
print(os.path.join('C:','D:\\','dir1','dir2','a.txt'))
print(os.path.join('D:\\','dir1','dir2','a.txt'))
print(os.path.normcase('c:/windows\\SYstem32\\..'))
print(os.path.normpath('c://windows\\System32\\../Temp/')) #C:\windows\temp
#F:\Python周末20期\day6\3 os模块.py\..\..
print(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
BASE_DIR=os.path.normpath(os.path.join(
os.path.abspath(__file__),
'..',
'..'
))
print(BASE_DIR)
# print(os.path.getsize(r'F:\Python周末20期\day6\1 本节内容'))
sys模块
import sys
sys.argv
sys.exit(0)
sys.path
print('[%-50s]' %('#'*1))
print('[%-50s]' %('#'*2))
print('[%-50s]' %('#'*3))
print('[%-50s]' %('#'*4))
print('[%-50s]' %('#'*5))
([%-50s]) %('#'*10)
print('[%%-%ds]' %50) #'[%-50s]'#
print(('[%%-%ds]' %50) %('#'*10)) #'[%-50s]' %('#'*10)
print(('[%%-%ds]' %50) %('#'*10)) #'[%-50s]' %('#'*10)
print(('[%%-%ds]' %50) %('#'*10)) #'[%-50s]' %('#'*10)
print(('[%%-%ds]' %50) %('#'*10)) #'[%-50s]' %('#'*10)
print('%d%%' %30)
shutil模块
import shutil
# shutil.make_archive("bak", 'gztar', root_dir=r'F:\Python周末20期\day6') #tar cvzf bak.tar.gz /root
# import tarfile
# t=tarfile.open('bak.tar.gz')
# t.extractall(r'F:\Python周末20期\day6\aaa')
# t.close()
json与pickle
dic={'a':1}
with open('db.txt','w',encoding='utf-8') as f:
f.write(str(dic))
with open('db.txt','r',encoding='utf-8') as f:
dic=eval(f.read()) #"{'a':1}"
print(dic['a'])
eval("[null,false,1]")
import json
dic={'a':1}
x=None
res1=json.dumps(dic) #str(dic)
res2=str(dic)
print(res1,type(res1))
print(res2,type(res2))
res=json.dumps(x)
print(res,type(res))
json序列化
import json,time
user={'name':'egon','age':18,'nb':True}
with open('user.json','w',encoding='utf-8') as f:
f.write(json.dumps(user))
students=['alex','egon','wxx','yxx']
json.dump(students,open('students.json','w',encoding='utf-8'))
time.sleep(500)
#pickle序列化
import pickle,json
s={1,2,3}
# print(json.dumps(s))
# print(pickle.dumps(s))
# with open('s.pkl','wb') as f:
# f.write(pickle.dumps(s))
pickle.dump(s,open('s.pkl','wb'))
json反序列化
import json
# with open('user.json','r',encoding='utf-8') as f:
# user=json.loads(f.read()) #json.dumps
# print(user['name'])
# user=json.load(open('user.json','r',encoding='utf-8'))
# print(user['age'])
# print(user['nb'])
# json_str='{"count":1}'
# print(json.loads(json_str)['count'])
# json_str="{'count':1}"
# print(json.loads(json_str))
# print(json.load(open('user.json','r',encoding='utf-8')))
#pickle反序列化
import pickle
# with open('s.pkl','rb') as f:
# s=pickle.loads(f.read())
# print(s,type(s))
s=pickle.load(open('s.pkl','rb'))
print(s, type(s))
shelve模块
# import shelve
#
# f=shelve.open('db.shl')
# # f['stu1']={'name':'alex1','age':38}
# # f['stu2']={'name':'alex2','age':28}
# print(f['stu1']['name'])
# f.close()
XML模块
from xml.etree import ElementTree
tree=ElementTree.parse('a.xml')
root=tree.getroot()
# print(root.tag)
# print(root.attrib)
# print(root.text)
#三种查找方式
#从子节点中找
# print(root.find('country'))
# print(root.findall('country'))
# print(root.find('rank')) #None
#从正树形结构中查找
# print(list(root.iter('rank')))
# for country in root.findall('country'):
# rank=country.find('rank')
# print(rank.tag,rank.attrib,rank.text)
#遍历文档树
# for country in root:
# print('=============>',country.attrib['name'])
# for item in country:
# print(item.tag,item.attrib,item.text)
# for year in root.iter('year'):
# print(year.tag,year.attrib,year.text)
# for year in root.iter('year'):
# year.set('updated',"yes")
# year.text=str(int(year.text)+1)
#
# tree.write('a.xml')
# for country in root:
# obj=ElementTree.Element('egon') #<egon name="egon" age="18">egon is good</egon>
# obj.attrib={'name':'egon','age':'18'}
# obj.text='egon is good'
# country.append(obj)
#
# tree.write('a.xml')
# for rank in root.iter('rank'):
# if int(rank.text) == 5:
# obj=ElementTree.Element('egon') #<egon name="egon" age="18">egon is good</egon>
# obj.attrib={'name':'egon','age':'18'}
# obj.text='egon is good'
# rank.append(obj)
#
# tree.write('a.xml')
configparser模块
import configparser
config=configparser.ConfigParser()
config.read('my.ini')
# print(config.sections())
# print(config.options('mysqld'))
# print(config.get('mysqld','charater-server-set'))
# if config.has_option('mysqld','aaa'):
# print(config.get('mysqld','aaa'))
# print(config.getboolean('mysqld','skip-grant-table'))
# print(config.getint('mysqld','port'))
# print(config.getfloat('mysqld','port'))
# config.add_section('egon')
# config.set('egon','name','egon')
# config.set('egon','age','18')
config.set('client','password','alex3714')
config.write(open('my.ini','w',encoding='utf-8'))
hashlib模块
import hashlib
# m=hashlib.md5()
# m.update('hello'.encode('utf-8'))
# m.update('world'.encode('utf-8'))
# m.update('world'.encode('utf-8'))
# m.update('world'.encode('utf-8'))
# m.update('world'.encode('utf-8'))
# m.update('world'.encode('utf-8'))
# m.update('world'.encode('utf-8'))
# m.update('world'.encode('utf-8'))
# m.update('world'.encode('utf-8'))
# m.update('world'.encode('utf-8'))
# m.update('world'.encode('utf-8'))
# print(m.hexdigest())
# fc5e038d38a57032085441e7fe7010b0
# m=hashlib.md5()
# m.update('hello'.encode('utf-8'))
# m.update('world'.encode('utf-8'))
# print(m.hexdigest())
#
# m1=hashlib.md5()
# m1.update('hellowor'.encode('utf-8'))
# m1.update('l'.encode('utf-8'))
# m1.update('d'.encode('utf-8'))
# print(m1.hexdigest())
# name=input('user:>> ')
# pwd=input('password:>> ')
# m=hashlib.md5()
# m.update(pwd.encode('utf-8'))
# pwd=m.hexdigest()
#
# print(name,pwd)
# cryt_pwd='aee949757a2e698417463d47acac93df'
# pwds=[
# 'alex3714',
# 'alex123',
# '123alex'
# ]
# def make_dic(pwds):
# dic={}
# for pwd in pwds:
# m=hashlib.md5(pwd.encode('utf-8'))
# dic[pwd]=m.hexdigest()
# return dic
#
# dic=make_dic(pwds)
# for pwd in dic:
# if dic[pwd] == cryt_pwd:
# print(pwd)
import hashlib
# m=hashlib.sha512()
# m=hashlib.md5('一行白鹭上青天'.encode('utf-8'))
# m.update('alex3714'.encode('utf-8'))
# m.update('两个黄鹂鸣翠柳'.encode('utf-8'))
# print(m.hexdigest())
# import hmac
# m=hmac.new('加盐'.encode('utf-8'))
# m.update('alex3714'.encode('utf-8'))
# print(m.hexdigest())
subprocess模块
# import subprocess
# import time
#
# subprocess.Popen('tasklist',shell=True)
# print('----->主')
# time.sleep(1)
# import subprocess
import time
#
# obj=subprocess.Popen('tasklist',shell=True,
# stdout=subprocess.PIPE,
# stderr=subprocess.PIPE,
# )
# print(obj)
# print('第1次:',obj.stdout.read())
# print('第2次:',obj.stdout.read())
# print('---->主')
# print(obj.stdout.read().decode('gbk'))
# import subprocess #ls /etc ;pwd;ps aux
# obj=subprocess.Popen('tssssasklist',shell=True,
# stdout=subprocess.PIPE,
# stderr=subprocess.PIPE,
# )
# print(obj.stdout.read())
# print(obj.stderr.read().decode('gbk'))
#了解
import subprocess #tasklist | findstr python
# obj=subprocess.Popen('tasklist | findstr python',shell=True,
# stdout=subprocess.PIPE,
# stderr=subprocess.PIPE,
# )
#
# print(obj.stdout.read())
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())