Python configparser 的基础使用(一)

作者: 伊洛的小屋 | 来源:发表于2020-02-15 12:31 被阅读0次
    1. 配置文件

    在编写程序时,会用到一些配置。一般配置都会写入.ini的文件。如果要使用python读取配置,就可以使用python自带的configparser模块

    本文首发于伊洛的个人博客:https://yiluotalk.com,欢迎关注并查看更多内容!!!

    2. ini文件结构
    • 键值对可以使用' = '' : ' 分隔
    • section区分大小写
    • key的名字不区分大小写
    • 键值对中头部、尾部的空白符被去掉
    • 配置文件注释以 #或者;为开头
    3. 简单的使用
    • 手写一个段代码生成ini文件
    # 伊洛Yiluo
    # https://yiluotalk.com
    import configparser
    config = configparser.ConfigParser()
    config['DEFAULT'] = {
        'ServerAliveInterval': '45',
        'Compression': 'yes',
        'CompressionLevel': '9'
    }
    config['bitbucket.org'] = {}
    config['bitbucket.org']['User'] = 'hg'
    config['topsectet.server.com'] = {}
    topsecret = config['topsectet.server.com']
    topsecret['Port'] = '50022'
    topsecret['ForwardX11'] = 'no'
    config['DEFAULT']['ForwardX11'] = 'yes'
    with open('example.ini', 'w') as configfile:
        config.write(configfile)
    
    • 查看生成的ini文件
    [DEFAULT]
    serveraliveinterval = 45
    compression = yes
    compressionlevel = 9
    forwardx11 = yes
    
    [bitbucket.org]
    user = hg
    
    [topsectet.server.com]
    port = 50022
    forwardx11 = no
    
    4. 读取配置文件
    • 现在读取配置文件
    >>> import configparser
    >>> config = configparser.ConfigParser()
    >>> config.sections()
    []
    
    
    • 由于没有读配置文件example.ini ,所以sections为空,现在读取下配置文件再查看下结果
    >>> config.read('example.ini')
    ['example.ini']
    >>> config.sections()
    ['bitbucket.org', 'topsectet.server.com']
    
    
    • 看到可以正常的读取到配置,再来单独的读取一条配置
    >>> config['bitbucket.org']['user']
    'hg'
    
    
    • 读取多条配置
    >>> for i in config['DEFAULT']:
    ...     print(i)
    ... 
    serveraliveinterval
    compression
    compressionlevel
    forwardx11
    
    
    5. 一般使用

    通常来讲一般公司都会有几套环境:开发环境、测试环境、灰度环境、生产环境
    在做接口自动化时就需要针对不同的环境跑对应的用例或是测试集,不同环境的配置就可以写入ini的配置文件方便后续调用

    # 伊洛Yiluo
    # https://yiluotalk.com
    [test_env]
    # 测试服配置
    tester = 伊洛yiluo
    environment = test
    host =
    login_name =
    login_password =
    
    
    [grey_env]
    # 灰度服配置
    tester = 伊洛yiluo
    environment = grey
    host =
    login_name =
    login_password =
    
    
    [release_env]
    # 正式配置
    tester = 伊洛yiluo
    environment = release
    host =
    login_name =
    login_password =
    
    
    [mail]
    # 邮件报告配置
    smtpserver =
    sender =
    receiver =
    username =
    password =
    
    
    [dingding]
    # dinging报告配置
    robot_url =
    messageUrl = 
    
    待续......

    关注公众号获取更多内容

    欢迎下方【戳一下】【点赞】
    Author:伊洛Yiluo
    愿你享受每一天,Just Enjoy !

    相关文章

      网友评论

        本文标题:Python configparser 的基础使用(一)

        本文链接:https://www.haomeiwen.com/subject/xfjjfhtx.html