Day29 of learning python --configparser和logging模块
1.configparser模块
该模式适用于配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键值)。因为这样就相当于操作字典一样方便
常见的文档格式如下:
[DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User = hg [topsecret.server.com] Port = 50022 ForwardX11 = no
如何生成这样一个类似的文档?
import configparser config = configparser.ConfigParser() config['DEFAULT'] = {'ServerAliveInterval':'45', 'Compression':'yes', 'CompressionnLevel':'9', 'ForwardXll':'yes'} config['bitbucket.org'] = {'User':'hg'} config['topsecret.server.com'] = {'Host Port':'50022','ForwardXll':'no'} with open('example.ini','w') as configfile: #写入文件中 config.write(configfile)
查找文件:
import configparser config = configparser.ConfigParser() #-------查找文件内容,基于字典的形式 print(config.sections()) # [] config.read('example.ini') # 先以读的方式,指定其文件 print(config.sections()) print('bytebong.com' in config) print('bitbucket.org' in config) print(config['bitbucket.org']['user']) print(config['DEFAULT']['compression']) print(config['topsecret.server.com']['forwardX11']) # 获取该section下键对应的value print(config['bitbucket.org']) for key in config['bitbucket.org']: #循环获取该section下的键值 print(key) print(config.options('bitbucket.org')) # 同for循环,找到'bitbucket.org'下所有键 print(config.items('bitbucket.org')) # 找到'bitbucket.org'下所有的键值对 print(config.get('topsecret.server.com','compression')) # get方法section下的key对应的value
增删改操作:
import configparser config = configparser.ConfigParser() config.read('example.ini') config.add_section('yuan') # 增加一个section config.remove_section('bitbucket.org') # 移除一个section config.remove_option('topsecret.server.com',"forwardx11") # 移除一个section下的键 config.set('topsecret.server.com','k1','11111') # 设置一个键值对 config.set('yuan','k2','22222') config.write(open('new2.ini', "w")) # 把上诉的修改,重新写到一个新的文件里面去,不能对原来的文件进行改和删的
2.logging模块
函数式简单配置
import logging logging.debug('debug message') # 低级别的,排错信息,细节信息 logging.info('info message') # 正常信息,用户操作 logging.warning('warning message') # 警告信息,不影响程序的运行 logging.error('error message') # 错误信息 报错 logging.critical('critical message') # 高级别的,严重错误信息 结果: WARNING:root:warning message ERROR:root:error message CRITICAL:root:critical message
默认情况下Python的logging模块将日志打印到标准输出中,且只显示了大于等于WARNING级别的日志,这说明默认的日志级别设置为WARNING(日志级别:CRITICAL>ERROR>WARNING>INFO>DEBUG),默认的日志格式为:日志级别:Logger名称:用户输出消息。
日志的作用:用来记录用户行为或者代码的执行过程,能够‘一键’控制,有一些用户行为有没有错都要记录下来
配置日志的级别,日志格式,输出位置:
import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', # 这个filename指的是那个文件的执行 datefmt='%a, %d %b %Y %H:%M:%S', # 时间格式 filename='test.log', # 输出到的文件 filemode='w') # 什么方法打开 logging.debug('debug message') logging.info('info message') logging.warning('warning message') logging.error('error message') logging.critical('critical message')
结果:
Fri, 07 Dec 2018 16:11:39 02 find.py[line:9] DEBUG debug message
Fri, 07 Dec 2018 16:11:39 02 find.py[line:10] INFO info message
Fri, 07 Dec 2018 16:11:39 02 find.py[line:11] WARNING warning message
Fri, 07 Dec 2018 16:11:39 02 find.py[line:12] ERROR error message
Fri, 07 Dec 2018 16:11:39 02 find.py[line:13] CRITICAL critical message
配置的参数:
logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为,可用参数有: filename:用指定的文件名创建FiledHandler,这样日志会被存储在指定的文件中。 filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。 format:指定handler使用的日志显示格式。 datefmt:指定日期时间格式。 level:设置rootlogger(后边会讲解具体概念)的日志级别 stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件(f=open(‘test.log’,’w’)),默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。 format参数中可能用到的格式化串: %(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用户输出的消息
# basicconfig 简单,能做的事情相对少 #解决不了中文乱码的问题 #不能同时往文件和屏幕输出 # 配置log对象 稍微有点复杂 能做的事情相对多
logger对象配置
import logging logger = logging.getLogger() # 创建一个handler,用于写入日志文件 fh = logging.FileHandler('test1.log',encoding='utf-8') # 再创建一个handler,用于输出到控制台 ch = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setLevel(logging.DEBUG)
ch.setLevel(logging.CRITICAL) fh.setFormatter(formatter) ch.setFormatter(formatter) logger.addHandler(fh) #logger对象可以添加多个fh和ch对象 logger.addHandler(ch) logger.debug('logger debug message') logger.info('logger info message') logger.warning('logger warning message') logger.error('logger error message') logger.critical('logger critical message')
另外,可以通过:logger.setLevel(logging.Debug)设置级别
浙公网安备 33010602011771号