configparser logging collections 模块

一:configparser模块

1,该模块用于配置文件(.ini的文件),该文件可以包含一个或多个节(section),每个节可以有多个参数(键=值)。

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
  
[bitbucket.org]
User = hg
  
[topsecret.server.com]
Port = 50022
ForwardX11 = no
常见的配置文件的格式

2,如何用python生产这样一个文件?

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 configfile:

   config.write(configfile)
View Code

3,查找文件

import configparser

config = configparser.ConfigParser()

#---------------------------查找文件内容,基于字典的形式

print(config.sections())        #  []

config.read('example.ini')

print(config.sections())        #   ['bitbucket.org', 'topsecret.server.com']

print('bytebong.com' in config) # False
print('bitbucket.org' in config) # True


print(config['bitbucket.org']["user"])  # hg

print(config['DEFAULT']['Compression']) #yes

print(config['topsecret.server.com']['ForwardX11'])  #no


print(config['bitbucket.org'])          #<Section: bitbucket.org>

for key in config['bitbucket.org']:     # 注意,有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
View Code

4,增删该操作

import configparser

config = configparser.ConfigParser()

config.read('example.ini')

config.add_section('yuan')



config.remove_section('bitbucket.org')
config.remove_option('topsecret.server.com',"forwardx11")


config.set('topsecret.server.com','k1','11111')
config.set('yuan','k2','22222')

config.write(open('new2.ini', "w"))
View Code

二:logging模块

1,简单配置

(1)

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)

(2),灵活配置日志级别,日志格式,输出位置

import logging
logging.basicConfig(level=logging.ERROR,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %y %H:%M:%S',
                    filename = 'userinfo.log')

logging.debug('debug message')       # debug 调试模式 级别最低
logging.info('info message')         # info  显示正常信息
logging.warning('warning message')   # warning 显示警告信息
logging.error('error message')       # error 显示错误信息
logging.critical('critical message') # critical 显示严重错误信息
View Code

(3),配置参数

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用户输出的消息
View Code

ps:简单配置的局限性在于:编码格式不能设置,而且不能同时输出到文件和屏幕。

2,logger对象配置

import logging
logger = logging.getLogger()  # 实例化了一个logger对象

# 实例化了一个文件句柄,用于写入日志
fh = logging.FileHandler('test.log',encoding='utf-8')
#再创建一个handler,用于输出到控制台
sh = logging.StreamHandler()

fmt = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(fmt)   # 格式和文件句柄或者屏幕句柄关联
sh.setFormatter(fmt)
sh.setLevel(logging.WARNING)  #指定从屏幕中输出WARNING级别以上的日志

# 吸星大法
logger.addHandler(fh)  # 和logger关联的只有句柄
logger.addHandler(sh)
logger.setLevel(logging.DEBUG)   #指定从文件中输出DEBUG级别以上的日志

logger.debug('debug message')       # debug 调试模式 级别最低
logger.info('info message')         # info  显示正常信息
logger.warning('warning message')   # warning 显示警告信息
logger.error('error message')       # error 显示错误信息
logger.critical('critical message')
View Code

3,logging模块总结

# logging
# logging 是记录日志的模块
# 它不能自己打印内容 只能根据程序员写的代码来完成功能
# logging模块提供5中日志级别,从低到高一次:debug info warning error critical
# 默认从warning模式开始显示
# 只显示一些基础信息,我们还可以对显示的格式做一些配置

# 简单配置 配置格式 basicCondfig
# 问题:编码问题,不能同时输出到文件和屏幕

# logger对象配置
# 高可定制化
# 首先创造logger对象
# 创造文件句柄 屏幕句柄
# 创造格式
# 使用文件句柄和屏幕句柄 绑定格式
# logger对象和句柄关联
# logger.setLevel
# 使用的时候 logger.debug
View Code

 三:collections模块

在内置数据类型(dict、list、set、tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter、deque、defaultdict、namedtuple和OrderedDict等

1.namedtuple: 生成可以使用名字来访问元素内容的tuple

2.deque: 双端队列,可以快速的从另外一侧追加和推出对象

3.Counter: 计数器,主要用来计数

4.OrderedDict: 有序字典,

使用dict时,Key是无序的。在对dict做迭代时,我们无法确定Key的顺序。

如果要保持Key的顺序,可以用OrderedDict

from collections import namedtuple
print(namedtuple('count',['x','y'])(1,2))
print(namedtuple('count',['x','y'])(1,2).x)
print(namedtuple('count',['x','y'])(1,2).y)
namedtuple
from collections import deque
dq = deque()
dq.append(1)
dq.append(2)
dq.append(3)
print(dq)
print(dq.pop())
print(dq.popleft())
dq.appendleft(4)
dq.appendleft(5)
print(dq)
双端队列 >>deque
# from collections import OrderedDict
# dic = OrderedDict([('k1','v1'),('k2','v2')])  #创建有序字典
# print(dic)

# from collections import OrderedDict
# d = OrderedDict()
# d['a'] = 1
# d['z'] = 2
# d['b'] = 3
# print(d)
# d['z'] = 0  #修改z的值
# print(d)
有序字典 >OrderedDict

5.defaultdict: 带有默认值的字典,默认字典是给字典中的value设置默认值,它最大的好处就是 永远不会在你使用key获取值的时候报错。

from collections import defaultdict
d = defaultdict(list)  #defaultdict(<class 'list'>, {})
print(d)   #[]
print(d['a'])  #没有给出value,默认value为空
d['b'] = 10
print(d)    #defaultdict(<class 'list'>, {'a': [], 'b': 10})
认识defaultdict

【例】有如下值集合[11,22,33,44,55,66,77,88,99,90],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。

即: {'k1': 大于66 'k2': 小于66}

#法一
dic = {}
l = [11,22,33,44,55,66,77,88,99,90]
for i in l:
    if i>66:
        if dic.get('k1'):
            dic['k1'].append(i)
        else:
            dic['k1'] = [i]
    elif i<66:
        if dic.get('k2'):
            dic['k2'].append(i)
        else:
            dic['k2'] = [i]
print(dic)
#法二
l = [11,22,33,44,55,66,77,88,99,90]
dic={}
for i in l:
    if i > 66:
        if 'k1' not in dic:
            dic['k1']=[i]
        else:
            dic['k1'].append(i)
    else:
        if 'k2' not in dic:
            dic['k2']=[i]
        else:
            dic['k2'].append(i)
print(dic)
原生字典解决方法
from collections import defaultdict
d = defaultdict(list)   #设置字典里的value的数据类型
l = [11,22,33,44,55,66,77,88,99,90]
for i in l:
    if i>66:
        d['k1'].append(i)
    elif i<66:
        d['k2'].append(i)
print(d)
defaultdict字典解决方法

 

posted @ 2018-04-24 19:38  扬帆起航111  阅读(147)  评论(0编辑  收藏  举报