【发布时间】:2014-03-13 01:15:08
【问题描述】:
是否可以从字符串或列表中读取ConfigParser 的配置?
文件系统上没有任何类型的临时文件
或
有没有类似的解决方案?
【问题讨论】:
标签: python python-2.7 configparser
是否可以从字符串或列表中读取ConfigParser 的配置?
文件系统上没有任何类型的临时文件
或
有没有类似的解决方案?
【问题讨论】:
标签: python python-2.7 configparser
您可以使用行为类似于文件的缓冲区: 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')
【讨论】:
cStringIO objects 不是buffers。 Strings 是缓冲区,但不能在需要file-like 对象的地方使用缓冲区; cStringIO 包装 buffer 以使其表现得像file。此外,您的示例并未演示 cStringIO 的行为方式类似于文件; getvalue 是特定于 cStringIO 实例的方法,但文件没有它。
config.readfp 已弃用,取而代之的是 config.read_file as of Python 3.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'))
【讨论】:
Python 从 3.2 版开始就有 read_string 和 read_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}')
【讨论】: