zoukankan      html  css  js  c++  java
  • python's twenty-sixth day for me 模块

    configparser 模块:

      该模块适用于配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键 = 值)。

      创建文件:

    #   创建文件
    import configparser
    config = configparser.ConfigParser()
    config['DEFAULT'] = {'SeverAliveInterval':'45',
                         'Compression':'yes',
                         'CompressionLevel':'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())    # ['bitbucket.org', 'topsecret.server.com']  除了DEFAULT的所有小节名
    print('bytebong.com' in config)     # False 查询小节名,存在返回True不存在则返回Falese
    print('bitbucket.org' in config)    # True
    print(config['bitbucket.org']['user'])      # hg
    print(config['DEFAULT']['compression'])     # yes
    print(config['topsecret.server.com']['ForwardXll'])     # no
    print(config['bitbucket.org'])  # <Section: bitbucket.org>  打印对象名[小节名] 相当于返回一个迭代器
    for i in config['bitbucket.org']:
        print(i)    #   将文件中指定小节的键打印出来,若是有DEFAULT则会将DEFAULT的键默认打印出来。
        # user
        # severaliveinterval
        # compressionlevel
        # forwardxll
        # forwardxll
    print(config.options('bitbucket.org'))  # ['user', 'forwardxll', 'compression', 'severaliveinterval', 'compressionlevel']
    # 将 小节名下的键以列表形式打印出来,若是有default则将default中的键也添加到列表中。
    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','forwardXll')
    
    config.set('topsecret.server.com','k1','1111')
    config.set('yuan','k2','2222')
    config.write(open('new2.ini','w'))  # 新建一个文件,把更改后的文件写入。

    logging 模块:

      1,记录日志的模块。

      2,它不能自己打印内容,只能根据程序员写的代码来完成功能。

      3,logging模块提供五种日志级别从低到高排序:debug , info , warning , error , critical

      4,只显示一些基础信息,可以对显示的格式做一些配置。

      函数式简单配置:

    # 函数式见配置
    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
    # 默认打印warning级别以上的所有日志。
    # 日志级别:criticla > error > warning > info> debug

      灵活配置日志级别,日志格式,输出位置:

    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 = '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')
    
    # 缺点:编码格式不能设置。
    #       不能同时输出到文件和屏幕。

      logger对象配置:

    import logging
    # logging.basicConfig(level = logging.DEBUG)
    logger = logging.getLogger()
    fh = logging.FileHandler('log',encoding='utf-8')    # 创建一个handler,用于写入日志文件。
    ch = logging.StreamHandler()    # 创建一个handler,用于输出控制台
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    fh.setLevel(level=logging.DEBUG)    # 对文件句柄设置等级。
    
    fh.setFormatter(formatter)     # 格式和文件句柄或者屏幕句柄关联
    ch.setFormatter(formatter)
    logger.addHandler(fh)   # logger对象可以添加多个fh和ch对象,和logger(对象)关联的只有句柄。
    logger.addHandler(ch)
    
    logging.debug('debug message')       # debug 调试模式 级别最低
    logging.info('info message')         # info  显示正常信息
    logging.warning('warning message')   # warning 显示警告信息
    logging.error('error message')       # error 显示错误信息
    logging.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用户输出的消息
    配置参数

    collections 模块:

      namedtuple:

    from collections import namedtuple
    Point = namedtuple('Point',['x','y'])
    p = Point(1,2)
    print(p.x)      # 1
    print(p.y)      # 2

      deque:

    from collections import deque
    # 双端队列
    dq = deque()
    dq.append(1)    # 默认依次往右添加。
    dq.append(2)
    dq.append(3)
    print(dq)   # deque([1, 2, 3])  类似于列表,但不是列表。
    print(dq.pop()) # 3 默认删除最后一个添加进去的。
    print(dq.popleft())    # 从左侧开始删除。
    dq.appendleft(4)        # 从左侧添加
    dq.appendleft(5)
    print(dq)   # deque([5, 4, 2])

      OrderedDict:

    from collections import OrderedDict
    dic = OrderedDict([['k1','v1'],['k3','v3'],['k2','v2']])
    print(dic)  # OrderedDict([('k1', 'v1'), ('k3', 'v1'), ('k2', 'v1')])
    dic = OrderedDict([('k1','v1'),('k2','v2'),('k3','v3')])
    print(dic)  # OrderedDic
    
    #子元素是列表或者元素都可以!

       defaultdict:

    from collections import defaultdict
    
    d = defaultdict(list)      
    print(d)    # defaultdict(<class 'list'>, {})
    l = [11,22,33,44,55,66,77,88,99]
    for i in l:
        if i>66:
            d['k1'].append(i)
        elif i<66:
            d['k2'].append(i)
    print(d)    # defaultdict(<class 'list'>, {'k1': [77, 88, 99], 'k2': [11, 22, 33, 44, 55]})
    # 默认字典最大的好处就是,永远不会再你使用key获取值的时候报错。
    # 默认字典 是给 字典中的 value设置默认值。

      Counter:

    from collections import Counter
    c = Counter('sdfsafsdfsa')
    print(c)    # Counter({'s': 4, 'f': 3, 'a': 2, 'd': 2})
    # 可以计算字符串每个元素出现的次数,并按次数从大到小排序
  • 相关阅读:
    JS 中的foreach和For in比较
    SQL 查询CET使用领悟
    .NET开源项目
    asp.net获取客户端IP方法(转载)
    jQuery Mobile 基础(第四章)
    jQuery Mobile 基础(第三章)
    jQuery Mobile 基础(第二章)
    机器学习笔记之梯度下降法
    特征脸是怎么提取的之主成分分析法PCA
    word2vec初探
  • 原文地址:https://www.cnblogs.com/stfei/p/8919690.html
Copyright © 2011-2022 走看看