zoukankan      html  css  js  c++  java
  • Python学习笔记29:configparse和logging模块

    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 configfile:
    
       config.write(configfile)

    结果:

    查找文件

    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

    结果:

    增删改

    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')
    
    f = open('new2.ini',"w")
    config.write(open('new2.ini', "w"))  # 改完后,必须要写回去
    f.close()

    结果:

    # logging
    # 能够“一键”控制
    # 排错的时候需要打印很多细节来帮助我排错
    # 严重的错误记录下来
    # 有一些用户行为 有没有错都要记录下来
    import logging
    logging.debug('debug message')       # 低级别的 # 排错信息
    logging.info('info message')            # 正常信息
    logging.warning('warning message')      # 警告信息
    logging.error('error message')          # 错误信息
    logging.critical('critical message') # 高级别的 # 严重错误信息

    结果:

    两种配置logging的方法,目的使得输出更全面,好看
    # basicconfig 简单 能做的事情相对少
        # 中文会有乱码问题
        # 不能同时往文件和屏幕上输出
    
    # 配置log对象 稍微有点复杂 能做的事情相对多,且灵活
    import logging
    logging.basicConfig(level=logging.DEBUG, # 要大写,输出级别,这个级别以上的都要输出
                        format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                        datefmt='%a, %d %b %Y %H:%M:%S',
                        filename='test.log',
                        filemode = 'a')
    logging.debug('debug message')       # 低级别的 # 排错信息
    logging.info('info message')            # 正常信息
    logging.warning('warning message')      # 警告信息
    logging.error('error message')          # 错误信息
    logging.critical('critical message') # 高级别的 # 严重错误信息

     # 格式化输出
     # print('%(key)s'%{'key':'value'}) # value

    # 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用户输出的消息
    import logging
    
    logger = logging.getLogger()
    
    fh = logging.FileHandler('test.log',encoding='utf-8') # 文件handler
    ch = logging.StreamHandler() # 输出到控制台
    
    # 设置输出格式
    formatter = logging.Formatter('%(asctime)s-%(name)s-%(levelno)s-%(levelname)s')
    fh.setLevel(logging.DEBUG)
    
    fh.setFormatter(formatter) # 文件操作符和格式关联
    ch.setFormatter(formatter) # 控制台操作符和格式关联
    
    # logger和操作符关联 ,可以关联多个
    logger.addHandler(fh)
    logger.addHandler(ch)
    
    logger.debug('logger debug message')
    logger.info('aa')
    logger.warning('bb')
    logger.error('cc')
    logger.critical('dd')

    结果:

  • 相关阅读:
    Thrift实现C#调用Java开发步骤详解
    微信小程序项目实战之豆瓣天气
    带有关闭按钮的alertView
    基于olami开放语义平台的微信小程序遥知之源码实现
    iOS-仿智联字符图片验证码
    微信 支付宝支付 友盟登录分享 统计
    优化VMware提高虚拟机运行速度的技巧
    区块链与密码学
    在 Ubuntu 16.04 中安装支持 CPU 和 GPU 的 Google TensorFlow 神经网络软件
    Ubuntu+anaconda环境里安装opencv
  • 原文地址:https://www.cnblogs.com/zheng1076/p/11166559.html
Copyright © 2011-2022 走看看