028_configparser模块,logging模块

 

configparser模块     生成配置文件

  • 该模块适用于配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。
  • 生成的配置文件作用和之前工程中设置的config.py文件一样,
  • 这种方式生成的配置文件有格式要求,配置文件的内容要以组的方式划分

1,生成配置文档

configparse
import configparser
config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45',
                      'Compression': 'yes',
                     'CompressionLevel': '9',
                     'ForwardX11':'yes'
                     }
config['bitbucket.org'] = {'User':'hg'}

config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'}

with open('example.ini', 'w') as f:
   config.write(f)

  

2,查找

import configparser

config = configparser.ConfigParser()

#---------------------------查找文件内容,基于字典的形式
#下面的语句请一块一块的使用,即将其它块的注释掉。

print(config.sections())        #>>>[]   #什么都拿不到,因为没指定读什么文件,但是不会报错

config.read('example.ini')	# 读取文件
print(config.sections())        #>>>['bitbucket.org', 'topsecret.server.com']  # 获取所有的组,“default”组比较特别是不会显示的。

print('bytebong.com' in config) # False  #查看组是否在这个文件里面
print('bitbucket.org' in config) # True


print(config['bitbucket.org']["user"])  # hg  #拿bitbucket.org组的user项
print(config['DEFAULT']['Compression']) #yes
print(config['topsecret.server.com']['ForwardX11'])  #no


print(config['bitbucket.org'])          #<Section: bitbucket.org>  #打印bitbucket.org的地址

for key in config['bitbucket.org']:    #打印组内所有的键,  # 注意,有default会默认打印default的键,而且不管通过那个组都能使用default的项
    print(key)

print(config.options('bitbucket.org'))  # 同for循环,找到'bitbucket.org'下所有键

print(config.items('bitbucket.org'))    #找到'bitbucket.org'下所有键值对

print(config.get('bitbucket.org','compression')) # yes       # get方法Section下的key对应的value

3,增删改操作

import configparser
config = configparser.ConfigParser()
config.read('example.ini')

config.add_section('yuan')   #增加一个yuan组 

config.remove_section('bitbucket.org')  #删除一个section
config.remove_option('topsecret.server.com',"forwardx11")   # 删除一个配置项

config.set('topsecret.server.com','k1','11111')  # 修改配置项,修改完还要写入。
config.set('yuan','k2','22222')
# f = open('new2.ini', "w")
# config.write(f) # 写进新文件,因为文件事实上是不能修改的
# f.close()

 

logging模块 日志

1,什么叫日志?

  日志 用来记录用户行为 或者 代码的执行过程

  # login  登录
  # log 日志
  # logging 日志

 

   logging 作用

# 我能够“一键”控制
# 排错的时候需要打印很多细节来帮助我排错
# 严重的错误记录下来
# 有一些用户行为 有没有错都要记录下来

 2,有四个级别

import logging
logging.debug('debug message')        # 排错信息  # 低级别的 
logging.info('info message')            # 正常信息
logging.warning('warning message')      # 警告信息
logging.error('error message')          # 错误信息
logging.critical('critical message')  # 严重错误信息  # 高级别的 

  默认情况下Python的logging模块将日志打印到了标准输出中,且只显示了大于等于WARNING级别的日志,这说明默认的日志级别设置为WARNING(日志级别等级CRITICAL > ERROR > WARNING > INFO > DEBUG),默认的日志格式为“日志级别:Logger名称:用户输出消息”。

3,配置

# basicconfig 简单 能做的事情相对少
    # 中文的乱码问题
    # 不能同时往文件和屏幕上输出
# logger对象配置 稍微有点复杂 能做的事情相对多
  3.1,basicconfig
import logging  
logging.basicConfig(level=logging.DEBUG,     #“level=logging.DEBUG”  表示显示DEBUG级别及以上级别的内容。
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',  #配置参数 # 格式化输出 print('%(key)s'%{'key':'value'}) # print('%s'%('key','value'))
                    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')

  

    3.1.2,配置参数  

 1 logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为,可用参数有:
 2 
 3 filename:用指定的文件名创建FiledHandler,这样日志会被存储在指定的文件中。
 4 filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
 5 format:指定handler使用的日志显示格式。
 6 datefmt:指定日期时间格式。
 7 level:设置rootlogger(后边会讲解具体概念)的日志级别
 8 stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件(f=open(‘test.log’,’w’)),默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。
 9 
10 format参数中可能用到的格式化串:
11 %(name)s Logger的名字
12 %(levelno)s 数字形式的日志级别
13 %(levelname)s 文本形式的日志级别
14 %(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
15 %(filename)s 调用日志输出函数的模块的文件名
16 %(module)s 调用日志输出函数的模块名
17 %(funcName)s 调用日志输出函数的函数名
18 %(lineno)d 调用日志输出函数的语句所在的代码行
19 %(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
20 %(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数
21 %(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
22 %(thread)d 线程ID。可能没有
23 %(threadName)s 线程名。可能没有
24 %(process)d 进程ID。可能没有
25 %(message)s用户输出的消息
配置参数

     3.1.3,basicconfig   在可能错误的地方进行记录。

import logging  
logging.basicConfig(level=logging.DEBUG,     #“level=logging.DEBUG”  表示显示DEBUG级别及以上级别的内容。
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',  #配置参数 # 格式化输出 print('%(key)s'%{'key':'value'}) # print('%s'%('key','value'))
                    datefmt='%a, %d %b %Y %H:%M:%S',   # 时间格式
                    filename='test.log',     #往文件里写   #去掉这两句,就输出到控制台。
                    filemode='w')  

try:
    int(input('num >>'))
except ValueError:
    logging.error('输入的值不是一个数字') 
 # 但是basicconfig记录的日志编码格式有问题,在文件中不能显示中文但在控制台没问题。

  3.4,logger对象配置

import logging

#创建一个logger对象,管智能输出
logger = logging.getLogger()  
# 创建一个handler,用于写入日志文件
fh = logging.FileHandler('test.log',encoding='utf-8') 

# 再创建一个handler,用于输出到控制台 
ch = logging.StreamHandler() 
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setLevel(logging.DEBUG)

fh.setFormatter(formatter)  # 文件操作符 和 格式关联
ch.setFormatter(formatter) 
logger.addHandler(fh) #logger对象可以添加多个fh和ch对象 
logger.addHandler(ch) # logger 对象 和 文件操作符 关联

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')

  

原文地址:https://www.cnblogs.com/eternity-twinkle/p/10644895.html