zoukankan      html  css  js  c++  java
  • 转 python 2 读取配置文件

    https://docs.python.org/2/library/configparser.html

    13.2.4. Examples

    An example of writing to a configuration file:

    import ConfigParser
    
    config = ConfigParser.RawConfigParser()
    
    # When adding sections or items, add them in the reverse order of
    # how you want them to be displayed in the actual file.
    # In addition, please note that using RawConfigParser's and the raw
    # mode of ConfigParser's respective set functions, you can assign
    # non-string values to keys internally, but will receive an error
    # when attempting to write to a file or when you get it in non-raw
    # mode. SafeConfigParser does not allow such assignments to take place.
    config.add_section('Section1')
    config.set('Section1', 'an_int', '15')
    config.set('Section1', 'a_bool', 'true')
    config.set('Section1', 'a_float', '3.1415')
    config.set('Section1', 'baz', 'fun')
    config.set('Section1', 'bar', 'Python')
    config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
    
    # Writing our configuration file to 'example.cfg'
    with open('example.cfg', 'wb') as configfile:
        config.write(configfile)
    

    An example of reading the configuration file again:

    import ConfigParser
    
    config = ConfigParser.RawConfigParser()
    config.read('example.cfg')
    
    # getfloat() raises an exception if the value is not a float
    # getint() and getboolean() also do this for their respective types
    a_float = config.getfloat('Section1', 'a_float')
    an_int = config.getint('Section1', 'an_int')
    print a_float + an_int
    
    # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
    # This is because we are using a RawConfigParser().
    if config.getboolean('Section1', 'a_bool'):
        print config.get('Section1', 'foo')
    

    To get interpolation, you will need to use a ConfigParser or SafeConfigParser:

    import ConfigParser
    
    config = ConfigParser.ConfigParser()
    config.read('example.cfg')
    
    # Set the third, optional argument of get to 1 if you wish to use raw mode.
    print config.get('Section1', 'foo', 0)  # -> "Python is fun!"
    print config.get('Section1', 'foo', 1)  # -> "%(bar)s is %(baz)s!"
    
    # The optional fourth argument is a dict with members that will take
    # precedence in interpolation.
    print config.get('Section1', 'foo', 0, {'bar': 'Documentation',
                                            'baz': 'evil'})
    

    Defaults are available in all three types of ConfigParsers. They are used in interpolation if an option used is not defined elsewhere.

    import ConfigParser
    
    # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
    config = ConfigParser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
    config.read('example.cfg')
    
    print config.get('Section1', 'foo')  # -> "Python is fun!"
    config.remove_option('Section1', 'bar')
    config.remove_option('Section1', 'baz')
    print config.get('Section1', 'foo')  # -> "Life is hard!"
    

    The function opt_move below can be used to move options between sections:

    def opt_move(config, section1, section2, option):
        try:
            config.set(section2, option, config.get(section1, option, 1))
        except ConfigParser.NoSectionError:
            # Create non-existent section
            config.add_section(section2)
            opt_move(config, section1, section2, option)
        else:
            config.remove_option(section1, option)
    

    Some configuration files are known to include settings without values, but which otherwise conform to the syntax supported by ConfigParser. The allow_no_value parameter to the constructor can be used to indicate that such values should be accepted:

    >>> import ConfigParser
    >>> import io
    
    >>> sample_config = """
    ... [mysqld]
    ... user = mysql
    ... pid-file = /var/run/mysqld/mysqld.pid
    ... skip-external-locking
    ... old_passwords = 1
    ... skip-bdb
    ... skip-innodb
    ... """
    >>> config = ConfigParser.RawConfigParser(allow_no_value=True)
    >>> config.readfp(io.BytesIO(sample_config))
    
    >>> # Settings with values are treated as before:
    >>> config.get("mysqld", "user")
    'mysql'
    
    >>> # Settings without values provide None:
    >>> config.get("mysqld", "skip-bdb")
    
    >>> # Settings which aren't specified still raise an error:
    >>> config.get("mysqld", "does-not-exist")
    Traceback (most recent call last):
      ...
    ConfigParser.NoOptionError: No option 'does-not-exist' in section: 'mysqld'
  • 相关阅读:
    对es6中Promise和async的理解
    js里面的map、filter、forEach、reduce、for in、for of等遍历方法
    浏览器怎么解析一个hmtl文档
    js获取浏览器版本
    js中的浅复制和深复制
    作为一个程序员,如何调试抓取跳转页面前发送的请求
    escape、unescape、encodeURIComponent、decodeURLComponent
    css超过一定长度显示省略号 强制换行
    gojs去除水印
    版本控制系统svn的超基础使用
  • 原文地址:https://www.cnblogs.com/feiyun8616/p/13503393.html
Copyright © 2011-2022 走看看