如何从字符串或列表中读取配置?

Luc*_*cas 20 python configparser python-2.7

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

或者
有没有类似的解决方案?

Noe*_*ans 29

您可以使用一个行为类似于文件的缓冲区:

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'))
Run Code Online (Sandbox Code Playgroud)


Seb*_*ian 18

问题被标记为python-2.7,但仅仅是为了完整性:从3.2开始,您可以使用ConfigParser函数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'))
Run Code Online (Sandbox Code Playgroud)