二,常用库(共15个
二,Python常用库(共15个) 1,os模块 2,json模块
3,random模块 4,string模块 5,异常处理 5.1 错误类型 5.1 逻辑错误两种处理方式 5.1.1 错误时可以预知的 5.1.2 错误时不可预知的
6,打码平台使用 7,时间模块 7.1 time 模块 7.2 datetime 模块 7.3 时间格式的转换 7.4 ,了解
8, sys模块
9,shutii 模块 10,pickle模块(有兼容性问题,了解就行) 11,xml模块 12,configparser模块(导入某种格式的配置文件)
13 hashlib 模块 14 subprocess模块 15,日志模块(logging) 15.1 日志级别 15.2 默认级别为warning,默认打印到终端 15.3 为logging模块指定全局配置,针对所有logger有效,控制打印到文件中 15.4 使用例子 15.5 logging模块的Formatter,Handler,Logger,Filter对象 15.6 Logger与Handler的级别 15.7 Logger的继承(了解) 15.8 应用 15.8.1 logging配置 15.8.2 使用 15.8.3 注意注意注意 15.8.4 另外一个django的配置,瞄一眼就可以,跟上面的一样
15.9 直奔主题,常规使用 15.9.1 日志级别与配置 15.9.2 日志配置字典(setting.py) 15.9.3 使用 15.9.4 日志轮换
16,struct模块
二,Python常用库(共15个)
1,os模块
import os
os. path. exists( )
os. path. join( )
os. path. join( path1, path2, path3)
os. makedirs( )
os. getcwd( )
os. chdir( "dirname" )
os. curdir
os. pardir
os. makedirs( 'dirname1/dirname2' )
os. removedirs( 'dirname1' )
os. mkdir( 'dirname' )
os. rmdir( 'dirname' )
os. listdir( 'dirname' )
os. remove( )
os. rename( "oldname" , "newname" )
os. stat( 'path/filename' )
os. sep
os. linesep
os. pathsep
os. name
os. system( "bash command" )
os. environ
os. path. abspath( path)
os. path. split( path)
os. path. dirname( path)
os. path. basename( path)
os. path. exists( path)
os. path. isabs( path)
os. path. isfile( path)
os. path. isdir( path)
os. path. join( path1[ , path2[ , . . . ] ] )
os. path. getatime( path)
os. path. getmtime( path)
os. path. getsize( path)
2,json模块
dic = json. loads( s)
s = json. dumps( dic)
import json
data = {
'name' : 'name' ,
'age' : 20 ,
}
json_str = json. dumps( data, ensure_ascii= False )
data = {
'name' : 'name' ,
'age' : 20 ,
}
filename = 'a.txt'
with open ( filename, 'w' ) as f:
json. dump( data , f)
data = {
'name' : 'name' ,
'age' : 20
}
filename = 'a.txt'
with open ( filename, 'w' ) as f:
json. dump( data, f)
with open ( filename) as f_:
print ( json. load( f_) )
2.1 猴子补丁S
import json
import ujson
def monkey_patch_json ( ) :
json. __name__ = 'ujson'
json. dumps = ujson. dumps
json. loads = ujson. loads
monkey_patch_json( )
3,random模块
a = random. choice( 'abcdefghijklmn' )
a = "abcdefghijklmnop1234567890"
b = random. sample( a, 3 )
num = random. randint( 1 , 100 )
1 ,random. random( )
2 ,random. randint( 1 , 3 )
3 ,random. randrange( 1 , 2 )
4 ,random. chioce( 'abcdefghijklmn' )
5 ,random. sample( [ 'a' , 'b' , 'c' , 'd' ] , 3 )
6 ,random. uniform( 1 , 3 )
item = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]
7 ,random. shuffle( item)
4,string模块
string. ascii_letters
string. ascii_uppercase
string. ascii_lowercase
string. punctuation
string. digits
5,异常处理
5.1 错误类型
if
File "<stdin>" , line 1
if
^
SyntaxError: invalid syntax
1 + ’2 ’
num= input ( ">>: " )
int ( num)
x
l= [ 'egon' , 'aa' ]
l[ 3 ]
dic= { 'name' : 'egon' }
dic[ 'age' ]
class Foo :
pass
Foo. x
1 / 0
5.1 逻辑错误两种处理方式
5.1.1 错误时可以预知的
age = input ( ">>:" ) . strip( )
if age. isdigit( ) :
age = int ( age)
if age > 18 :
print ( "猜大了" )
else :
print ( '猜小了' )
5.1.2 错误时不可预知的
try :
except 异常类型1 as e:
pass
except 异常类型2 as e:
pass
. . . .
else :
finally :
try :
print ( '11111111111' )
l = [ 'aaa' , 'bbbb' ]
l[ 3 ]
print ( '222222222222222' )
xxx
print ( '3333333333333333333' )
dic = { 'a' : 1 }
dic[ 'a' ]
print ( 'end' )
except IndexError as e:
print ( '异常处理了' )
print ( e)
except NameError as e:
print ( '异常处理了' )
print ( e)
print ( 'start' )
try :
print ( '11111111111' )
l = [ 'aaa' , 'bbbb' ]
l[ 3 ]
print ( '222222222222222' )
print ( '3333333333333333333' )
dic = { 'a' : 1 }
dic[ 'a' ]
print ( 'end' )
except ( IndexError, NameError) as e:
print ( '异常处理了' )
except KeyError as e:
print ( '字典的key不存在' , e)
print ( 'start' )
try :
print ( '11111111111' )
l = [ 'aaa' , 'bbbb' ]
l[ 3 ]
print ( '222222222222222' )
print ( '3333333333333333333' )
dic = { 'a' : 1 }
dic[ 'a' ]
print ( 'end' )
except Exception as e:
print ( '万能异常' )
try :
print ( '11111111111111' )
print ( '33333333333' )
print ( '2222222222222222222' )
except Exception as e:
print ( '所有异常都能匹配到' )
else :
print ( '==============>' )
print ( 'end...........' )
print ( 'start' )
try :
print ( '11111111111' )
l = [ 'aaa' , 'bbbb' ]
l[ 3 ]
print ( '222222222222222' )
xxx
print ( '3333333333333333333' )
dic = { 'a' : 1 }
dic[ 'a' ]
print ( 'end' )
finally :
print ( '我不处理异常,无论是否发生异常我都会运行' )
6,打码平台使用
import base64
import json
import requests
def base64_api ( uname, pwd, img, typeid) :
with open ( img, 'rb' ) as f:
base64_data = base64. b64encode( f. read( ) )
b64 = base64_data. decode( )
data = { "username" : uname, "password" : pwd, "typeid" : typeid, "image" : b64}
result = json. loads( requests. post( "http://api.ttshitu.com/predict" , json= data) . text)
if result[ 'success' ] :
return result[ "data" ] [ "result" ]
else :
return result[ "message" ]
return ''
if __name__ == "__main__" :
img_path = "./code.png"
result = base64_api( uname= 'xxxxx' , pwd= 'xxxxx' , img= img_path, typeid= 3 )
print ( result)
import base64
import json
import requests
def base64_api ( uname, pwd, img, typeid) :
with open ( img, 'rb' ) as f:
base64_data = base64. b64encode( f. read( ) )
b64 = base64_data. decode( )
data = { "username" : uname, "password" : pwd, "typeid" : typeid, "image" : b64}
result = json. loads( requests. post( "http://api.ttshitu.com/predict" , json= data) . text)
if result[ 'success' ] :
return result[ "data" ] [ "result" ]
else :
return result[ "message" ]
return ""
if __name__ == "__main__" :
img_path = "C:/Users/Administrator/Desktop/file.jpg"
result = base64_api( uname= '你的账号' , pwd= '你的密码' , img= img_path, typeid= 3 )
print ( result)
7,时间模块
7.1 time 模块
import time
time. time( )
time. strftime( '%Y-%m-%d %H:%M:%S %p' )
time. strftime( '%Y-%m-%d %X' )
res = time. localtime( )
print ( res)
print ( res. tm_year)
print ( res. tm_mon)
print ( res. tm_mday)
print ( res. tm_hour)
print ( res. tm_min)
print ( res. tm_sec)
print ( res. tm_wday)
print ( res. tm_yday)
print ( res. tm_isdst)
7.2 datetime 模块
import datetime
datetime. datetime. now( )
datetime. datetime. now( ) + datetime. timedelta( days = 3 )
7.3 时间格式的转换
import time
1 ,时间戳 < - - - - - - - - - - - - - - - - - > 结构化时间
s_time = time. localtime( )
res = time. mktime( s_time)
print ( res)
tp_time = time. time( )
res = time. localtime( tp_time)
print ( res)
tp_time = time. time( )
res = time. gmtime( tp_time)
print ( res)
2 , 结构化 < - - - - - - - - - - - - - - - - - - - - - - - - - > 格式化时间
res = time. strptime( '1988-03-03 11:11:11' , '%Y-%m-%d %H:%M:%S' )
print ( res)
'1988-03-03 11:11:11' + 7 - - - - - - - - - - - - - - - - - - - - - - - > 结构化时间
s_time = time. strptime( '1988-03-03 11:11:11' , '%Y-%m-%d %H:%M:%S' )
miao = time. mktime( s_time) + 7 * 86400
struct_time = time. localtime( miao)
res = time. strftime( '%Y-%m-%d %X' , time. localtime( miao) )
print ( res)
7.4 ,了解
import time
print ( time. asctime( ) )
8, sys模块
1 sys. argv
2 sys. exit( n)
3 sys. version
4 sys. maxint
5 sys. path
6 sys. platform
8.1 打印进度条
import time
def process ( ) :
recv_size = 0
total_size = 333333
while recv_size < total_size:
time. sleep( 0.05 )
recv_size += 1024
if recv_size > total_size:
recv_size = total_size
percent = recv_size / total_size
res = int ( 50 * percent) * "#"
print ( '\r[%-50s] %d%%' % ( res, 100 * percent) , end= '' )
process( )
9,shutii 模块
import shutill
shutil. copyfileobj( open ( 'old.xml' , 'r' ) , open ( 'new.xml' , 'w' ) )
shutil. copymode( 'f1.log' , 'f2.log' )
shutil. copyfile( 'f1.log' , 'f2.log' )
shutil. copystat( 'f1.log' , 'f2.log' )
shutil. copy( 'f1.log' , 'f2.log' )
shutil. copy2( 'f1.log' , 'f2.log' )
shutil. copytree( 'folder1' , 'folder2' , ignore= shutil. ignore_patterns( '*.pyc' , 'tmp*' ) )
shutil. copytree( 'f1' , 'f2' , symlinks= True , ignore= shutil. ignore_patterns( '*.pyc' , 'tmp*' ) )
'''
通常的拷贝都把软连接拷贝成硬链接,即对待软连接来说,创建新的文件
'''
shutil. rmtree( 'folder1' )
shutil. move( 'folder1' , 'folder3' )
base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
format : 压缩包种类,“zip ”, “tar”, “bztar”,“gztar”
root_dir: 要压缩的文件夹路径(默认当前目录)
owner: 用户,默认当前用户
group: 组,默认当前组
logger: 用于记录日志,通常是logging. Logger对象
ret = shutil. make_archive( "data_bak" , 'gztar' , root_dir= '/data' )
ret = shutil. make_archive( "/tmp/data_bak" , 'gztar' , root_dir= '/data' )
import zipfile
z = zipfile. ZipFile( 'laxi.zip' , 'w' )
z. write( 'a.log' )
z. write( 'data.data' )
z. close( )
z = zipfile. ZipFile( 'laxi.zip' , 'r' )
z. extractall( path= '.' )
z. close( )
import tarfile
t= tarfile. open ( '/tmp/egon.tar' , 'w' )
t. add( '/test1/a.py' , arcname= 'a.bak' )
t. add( '/test1/b.py' , arcname= 'b.bak' )
t. close( )
t= tarfile. open ( '/tmp/egon.tar' , 'r' )
t. extractall( '/egon' )
t. close( )
10,pickle模块(有兼容性问题,了解就行)
import pickle
res = pickle. dumps( { 1 , 2 , 3 , 4 , 5 } )
print ( res)
res = pickle. loads( res)
print ( res)
import pickle
with open ( 'a.pkl' , mode= 'wb' ) as f:
pickle. dump( '你好啊' , f, protocol= 2 )
with open ( 'a.pkl' , mode= 'rb' ) as f:
res= pickle. load( f)
print ( res)
11,xml模块
< ?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协议在各个语言里的都 是支持的,在python中可以用以下模块操作xml:
import xml. etree. ElementTree as ET
tree = ET. parse( "xmltest.xml" )
root = tree. getroot( )
print ( root. tag)
for child in root:
print ( '========>' , child. tag, child. attrib, child. attrib[ 'name' ] )
for i in child:
print ( i. tag, i. attrib, i. text)
for node in root. iter ( 'year' ) :
print ( node. tag, node. text)
import xml. etree. ElementTree as ET
tree = ET. parse( "xmltest.xml" )
root = tree. getroot( )
for node in root. iter ( 'year' ) :
new_year= int ( node. text) + 1
node. text= str ( new_year)
node. set ( 'updated' , 'yes' )
node. set ( 'version' , '1.0' )
tree. write( 'test.xml' )
for country in root. findall( 'country' ) :
rank = int ( country. find( 'rank' ) . text)
if rank > 50 :
root. remove( country)
tree. write( 'output.xml' )
import xml. etree. ElementTree as ET
tree = ET. parse( "a.xml" )
root= tree. getroot( )
for country in root. findall( 'country' ) :
for year in country. findall( 'year' ) :
if int ( year. text) > 2000 :
year2= ET. Element( 'year2' )
year2. text= '新年'
year2. attrib= { 'update' : 'yes' }
country. append( year2)
tree. write( 'a.xml.swap' )
自己创建xml文档:
import xml. etree. ElementTree as ET
new_xml = ET. Element( "namelist" )
name = ET. SubElement( new_xml, "name" , attrib= { "enrolled" : "yes" } )
age = ET. SubElement( name, "age" , attrib= { "checked" : "no" } )
sex = ET. SubElement( name, "sex" )
sex. text = '33'
name2 = ET. SubElement( new_xml, "name" , attrib= { "enrolled" : "no" } )
age = ET. SubElement( name2, "age" )
age. text = '19'
et = ET. ElementTree( new_xml)
et. write( "test.xml" , encoding= "utf-8" , xml_declaration= True )
ET. dump( new_xml)
12,configparser模块(导入某种格式的配置文件)
## 配置文件内容
[section1]
k1 = v1
k2:v2
user=egon
age=18
is_admin=true
salary=31
[section2]
k1 = v1
12.1 读取
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
12.2 改写
import configparser
config= configparser. ConfigParser( )
config. read( 'a.cfg' , encoding= 'utf-8' )
config. remove_section( 'section2' )
config. remove_option( 'section1' , 'k1' )
config. remove_option( 'section1' , 'k2' )
print ( config. has_section( 'section1' ) )
print ( config. has_option( 'section1' , '' ) )
config. add_section( 'egon' )
config. set ( 'egon' , 'name' , 'egon' )
config. set ( 'egon' , 'age' , 18 )
config. write( open ( 'a.cfg' , 'w' ) )
13 hashlib 模块
# hash是一类算法,该算法根据传入的内容,经过运算得到一串哈希值
# hash值的特单
1,传入的内容一样,则得到的结果一样
2,无论传多大内容,得到的hash值长度一样
3,不能反向破解
14 subprocess模块
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,stderr= subprocess. PIPE)
print ( res2. stdout. read( ) )
print ( res1. stderr. read( ) )
res= subprocess. Popen( 'grep txt$' , shell= True , stdin= res1. stdout, stdout= subprocess. PIPE)
print ( res. stdout. read( ) . decode( 'utf-8' ) )
res1= subprocess. Popen( 'ls /Users/jieli/Desktop |grep txt$' , shell= True , stdout= subprocess. PIPE)
print ( res1. stdout. read( ) . decode( 'utf-8' ) )
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' ) )
15,日志模块(logging)
15.1 日志级别
import logging
CRITICAL = 50
ERROR = 40
WARNING = 30
INFO = 20
DEBUG = 10
NOTSET = 0
15.2 默认级别为warning,默认打印到终端
import logging
logging. debug( '调试debug' )
logging. info( '消息info' )
logging. warning( '警告warn' )
logging. error( '错误error' )
logging. critical( '严重critical' )
'''
WARNING:root:警告warn
ERROR:root:错误error
CRITICAL:root:严重critical
'''
15.3 为logging模块指定全局配置,针对所有logger有效,控制打印到文件中
'''
可在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参数会被忽略。
'''
logging. basicConfig(
format = '%(asctime)s - %(name)s - %(levelname)s - %(module)s'
)
format 参数中可能用到的格式化串:
% ( name) s
% ( levelno) s
% ( levelname) s
% ( pathname) s
% ( filename) s
% ( module) s
% ( funcName) s
% ( lineno) d
% ( created) f
% ( relativeCreated) d
% ( asctime) s
% ( thread) d
% ( threadName) s
% ( process) d
% ( message) s
15.4 使用例子
#========使用
import logging
logging.basicConfig(
## 写到文件里的编码格式以系统编码格式为准,Windows为gbk
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')
logging.info('消息info')
logging.warning('警告warn')
logging.error('错误error')
logging.critical('严重critical')
#========结果
access.log内容:
2017-07-28 20:32:17 PM - root - DEBUG -test: 调试debug
2017-07-28 20:32:17 PM - root - INFO -test: 消息info
2017-07-28 20:32:17 PM - root - WARNING -test: 警告warn
2017-07-28 20:32:17 PM - root - ERROR -test: 错误error
2017-07-28 20:32:17 PM - root - CRITICAL -test: 严重critical
15.5 logging模块的Formatter,Handler,Logger,Filter对象
'''
critical=50
error =40
warning =30
info = 20
debug =10
'''
import logging
logger= logging. getLogger( __file__)
h1= logging. FileHandler( 't1.log' )
h2= logging. FileHandler( 't2.log' )
h3= logging. StreamHandler( )
formmater1= logging. Formatter(
'%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s' ,
datefmt= '%Y-%m-%d %H:%M:%S %p' ,
)
formmater2= logging. Formatter(
'%(asctime)s : %(message)s' ,
datefmt= '%Y-%m-%d %H:%M:%S %p' ,
)
formmater3= logging. Formatter( '%(name)s %(message)s' , )
h1. setFormatter( formmater1)
h2. setFormatter( formmater2)
h3. setFormatter( formmater3)
logger. addHandler( h1)
logger. addHandler( h2)
logger. addHandler( h3)
logger. setLevel( 10 )
logger. debug( 'debug' )
logger. info( 'info' )
logger. warning( 'warning' )
logger. error( 'error' )
logger. critical( 'critical' )
15.6 Logger与Handler的级别
import logging
form= logging. Formatter(
'%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s' ,
datefmt= '%Y-%m-%d %H:%M:%S %p' ,
)
ch= logging. StreamHandler( )
ch. setFormatter( form)
ch. setLevel( 20 )
l1= logging. getLogger( 'root' )
l1. setLevel( 10 )
l1. addHandler( ch)
l1. debug( 'l1 debug' )
15.7 Logger的继承(了解)
import logging
formatter= logging. Formatter( '%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s' ,
datefmt= '%Y-%m-%d %H:%M:%S %p' , )
ch= logging. StreamHandler( )
ch. setFormatter( formatter)
logger1= logging. getLogger( 'root' )
logger2= logging. getLogger( 'root.child1' )
logger3= logging. getLogger( 'root.child1.child2' )
logger1. addHandler( ch)
logger2. addHandler( ch)
logger3. addHandler( ch)
logger1. setLevel( 10 )
logger2. setLevel( 10 )
logger3. setLevel( 10 )
logger1. debug( 'log1 debug' )
logger2. debug( 'log2 debug' )
logger3. debug( 'log3 debug' )
'''
2017-07-28 22:22:05 PM - root - DEBUG -test: log1 debug
2017-07-28 22:22:05 PM - root.child1 - DEBUG -test: log2 debug
2017-07-28 22:22:05 PM - root.child1 - DEBUG -test: log2 debug
2017-07-28 22:22:05 PM - root.child1.child2 - DEBUG -test: log3 debug
2017-07-28 22:22:05 PM - root.child1.child2 - DEBUG -test: log3 debug
2017-07-28 22:22:05 PM - root.child1.child2 - DEBUG -test: log3 debug
'''
15.8 应用
15.8.1 logging配置
"""
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]'
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__) )
logfile_name = 'all2.log'
if not os. path. isdir( logfile_dir) :
os. mkdir( logfile_dir)
logfile_path = os. path. join( logfile_dir, logfile_name)
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'
} ,
'default' : {
'level' : 'DEBUG' ,
'class' : 'logging.handlers.RotatingFileHandler' ,
'formatter' : 'standard' ,
'filename' : logfile_path,
'maxBytes' : 1024 * 1024 * 5 ,
'backupCount' : 5 ,
'encoding' : 'utf-8' ,
} ,
} ,
'loggers' : {
'' : {
'handlers' : [ 'default' , 'console' ] ,
'level' : 'DEBUG' ,
'propagate' : True ,
} ,
} ,
}
def load_my_logging_cfg ( ) :
logging. config. dictConfig( LOGGING_DIC)
logger = logging. getLogger( __name__)
logger. info( 'It works!' )
if __name__ == '__main__' :
load_my_logging_cfg( )
15.8.2 使用
"""
MyLogging Test
"""
import time
import logging
import my_logging # 导入自定义的logging配置
logger = logging.getLogger(__name__) # 生成logger实例
def demo():
logger.debug("start range... time:{}".format(time.time()))
logger.info("中文测试开始。。。")
for i in range(10):
logger.debug("i:{}".format(i))
time.sleep(0.2)
else:
logger.debug("over range... time:{}".format(time.time()))
logger.info("中文测试结束。。。")
if __name__ == "__main__":
my_logging.load_my_logging_cfg() # 在你程序文件的入口加载自定义logging配置
demo()
15.8.3 注意注意注意
"""
MyLogging Test
"""
import time
import logging
import my_logging # 导入自定义的logging配置
logger = logging.getLogger(__name__) # 生成logger实例
def demo():
logger.debug("start range... time:{}".format(time.time()))
logger.info("中文测试开始。。。")
for i in range(10):
logger.debug("i:{}".format(i))
time.sleep(0.2)
else:
logger.debug("over range... time:{}".format(time.time()))
logger.info("中文测试结束。。。")
if __name__ == "__main__":
my_logging.load_my_logging_cfg() # 在你程序文件的入口加载自定义logging配置
demo()
15.8.4 另外一个django的配置,瞄一眼就可以,跟上面的一样
#logging_config.py
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]'
'[%(levelname)s][%(message)s]'
},
'simple': {
'format': '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
},
'collect': {
'format': '%(message)s'
}
},
'filters': {
'require_debug_true': {
'()': 'django.utils.log.RequireDebugTrue',
},
},
'handlers': {
#打印到终端的日志
'console': {
'level': 'DEBUG',
'filters': ['require_debug_true'],
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
#打印到文件的日志,收集info及以上的日志
'default': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件,自动切
'filename': os.path.join(BASE_LOG_DIR, "xxx_info.log"), # 日志文件
'maxBytes': 1024 * 1024 * 5, # 日志大小 5M
'backupCount': 3,
'formatter': 'standard',
'encoding': 'utf-8',
},
#打印到文件的日志:收集错误及以上的日志
'error': {
'level': 'ERROR',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件,自动切
'filename': os.path.join(BASE_LOG_DIR, "xxx_err.log"), # 日志文件
'maxBytes': 1024 * 1024 * 5, # 日志大小 5M
'backupCount': 5,
'formatter': 'standard',
'encoding': 'utf-8',
},
#打印到文件的日志
'collect': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件,自动切
'filename': os.path.join(BASE_LOG_DIR, "xxx_collect.log"),
'maxBytes': 1024 * 1024 * 5, # 日志大小 5M
'backupCount': 5,
'formatter': 'collect',
'encoding': "utf-8"
}
},
'loggers': {
#logging.getLogger(__name__)拿到的logger配置
'': {
'handlers': ['default', 'console', 'error'],
'level': 'DEBUG',
'propagate': True,
},
#logging.getLogger('collect')拿到的logger配置
'collect': {
'handlers': ['console', 'collect'],
'level': 'INFO',
}
},
}
# -----------
# 用法:拿到俩个logger
logger = logging.getLogger(__name__) #线上正常的日志
collect_logger = logging.getLogger("collect") #领导说,需要为领导们单独定制领导们看的日志
15.9 直奔主题,常规使用
15.9.1 日志级别与配置
import logging
logging. basicConfig(
format = '%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s' ,
datefmt= '%Y-%m-%d %H:%M:%S %p' ,
level= 30 ,
)
logging. debug( '调试debug' )
logging. info( '消息info' )
logging. warning( '警告warn' )
logging. error( '错误error' )
logging. critical( '严重critical' )
'''
# 注意下面的root是默认的日志名字
WARNING:root:警告warn
ERROR:root:错误error
CRITICAL:root:严重critical
'''
15.9.2 日志配置字典(setting.py)
"""
logging配置
在 setting.py中定义
"""
import os
standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
'[%(levelname)s][%(message)s]'
simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
test_format = '%(asctime)s] %(message)s'
LOGGING_DIC = {
'version' : 1 ,
'disable_existing_loggers' : False ,
'formatters' : {
'standard' : {
'format' : standard_format
} ,
'simple' : {
'format' : simple_format
} ,
'test' : {
'format' : test_format
} ,
} ,
'filters' : { } ,
'handlers' : {
'console' : {
'level' : 'DEBUG' ,
'class' : 'logging.StreamHandler' ,
'formatter' : 'simple'
} ,
'default' : {
'level' : 'DEBUG' ,
'class' : 'logging.handlers.RotatingFileHandler' ,
'formatter' : 'standard' ,
'filename' : 'a1.log' ,
'maxBytes' : 1024 * 1024 * 5 ,
'backupCount' : 5 ,
'encoding' : 'utf-8' ,
} ,
'other' : {
'level' : 'DEBUG' ,
'class' : 'logging.FileHandler' ,
'formatter' : 'test' ,
'filename' : 'a2.log' ,
'encoding' : 'utf-8' ,
} ,
} ,
'loggers' : {
'kkk' : {
'handlers' : [ 'default' , 'console' ] ,
'level' : 'DEBUG' ,
'propagate' : False ,
} ,
'bbb' : {
'handlers' : [ 'console' ] ,
'level' : 'DEBUG' ,
'propagate' : False ,
} ,
'专门的采集' : {
'handlers' : [ 'other' , ] ,
'level' : 'DEBUG' ,
'propagate' : False ,
} ,
} ,
}
15.9.3 使用
import settings
from logging import config
from logging import getLogger
logging. config. dictConfig( settings. LOGGING_DIC)
logger1 = getLogger( "kkk" )
logger2 = getLogger( 'bbb' )
logger1= logging. getLogger( '用户交易' )
logger1. info( 'egon儿子alex转账3亿冥币' )
15.9.4 日志轮换
'default' : {
'level' : 'DEBUG' ,
'class' : 'logging.handlers.RotatingFileHandler' ,
'formatter' : 'standard' ,
'filename' : 'a1.log' ,
'maxBytes' : 1024 * 1024 * 5 ,
'backupCount' : 5 ,
'encoding' : 'utf-8' ,
} ,
16,struct模块
import struct
bytes = struct. pack( 'i' , 1000 )
num = struct. unpack( 'i' , bytes ) [ 0 ]