【问题标题】:How to read config from string or list?如何从字符串或列表中读取配置?
【发布时间】:2014-03-13 01:15:08
【问题描述】:

是否可以从字符串或列表中读取ConfigParser 的配置?
文件系统上没有任何类型的临时文件


有没有类似的解决方案?

【问题讨论】:

    标签: python python-2.7 configparser


    【解决方案1】:

    您可以使用行为类似于文件的缓冲区: Python 3 解决方案

    import configparser
    import io
    
    s_config = """
    [example]
    is_real: False
    """
    buf = io.StringIO(s_config)
    config = configparser.ConfigParser()
    config.read_file(buf)
    print(config.getboolean('example', 'is_real'))
    

    Python 2.7 中,这个实现是正确的:

    import ConfigParser
    import StringIO
    
    s_config = """
    [example]
    is_real: False
    """
    buf = StringIO.StringIO(s_config)
    config = ConfigParser.ConfigParser()
    config.readfp(buf)
    print config.getboolean('example', 'is_real')
    

    【讨论】:

    • 那么在哪里使用缓冲区? ConfigParser.Read() 不包括文件名。
    • cStringIO objects 不是buffersStrings 是缓冲区,但不能在需要file-like 对象的地方使用缓冲区; cStringIO 包装 buffer 以使其表现得像file。此外,您的示例并未演示 cStringIO 的行为方式类似于文件; getvalue 是特定于 cStringIO 实例的方法,但文件没有它。
    • @Lucas 我已经发布了一个完整的示例,它采用 StringIO 缓冲区并获取示例值
    • 请注意,config.readfp 已弃用,取而代之的是 config.read_file as of Python 3.2
    【解决方案2】:

    问题被标记为 python-2.7,但只是为了完整起见:从 3.2 开始,您可以使用 ConfigParser function read_string(),因此您不再需要 StringIO 方法。

    import configparser
    
    s_config = """
    [example]
    is_real: False
    """
    config = configparser.ConfigParser()
    config.read_string(s_config)
    print(config.getboolean('example', 'is_real'))
    

    【讨论】:

    【解决方案3】:

    Python 从 3.2 版开始就有 read_stringread_dict。它不支持从列表中读取。

    该示例显示从字典中读取。键是部分名称,值是包含键和值的字典,应该存在于该部分中。

    #!/usr/bin/env python3
    
    import configparser
    
    cfg_data = {
        'mysql': {'host': 'localhost', 'user': 'user7',
                  'passwd': 's$cret', 'db': 'ydb'}
    }
    
    config = configparser.ConfigParser()
    config.read_dict(cfg_data)
    
    host = config['mysql']['host']
    user = config['mysql']['user']
    passwd = config['mysql']['passwd']
    db = config['mysql']['db']
    
    print(f'Host: {host}')
    print(f'User: {user}')
    print(f'Password: {passwd}')
    print(f'Database: {db}')
    

    【讨论】:

      猜你喜欢
      • 2015-02-28
      • 1970-01-01
      • 2021-02-22
      • 2019-09-13
      • 2013-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-24
      相关资源
      最近更新 更多