问题
Is it possible to read the configuration for ConfigParser
from a string or list?
Without any kind of temporary file on a filesystem
OR
Is there any similar solution for this?
回答1:
You could use a buffer which behaves like a file: Python 3 solution
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'))
In Python 2.7, this implementation was correct:
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')
回答2:
The question was tagged as python-2.7 but just for the sake of completeness: Since 3.2 you can use the ConfigParser function read_string() so you don't need the StringIO method anymore.
import configparser
s_config = """
[example]
is_real: False
"""
config = configparser.ConfigParser()
config.read_string(s_config)
print(config.getboolean('example', 'is_real'))
回答3:
Python has read_string
and read_dict
since version 3.2. It does not support reading from lists.
The example shows reading from a dictionary. Keys are section names, values are dictionaries with keys and values that should be present in the section.
#!/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}')
回答4:
This may also be useful. It shows you how to read strings using a config (CFG file). Here's a basic config reader I made with the info I've gathered from the Internet:
import configparser as cp
config = cp.ConfigParser()
config.read('config.cfg')
opt1=config.getfloat('Section1', 'option1')
opt2=config.getfloat('Section1', 'option2')
opt3=config.get('Section1', 'option3')
print('Config File Float Importer example made using\n\
http://stackoverflow.com/questions/18700295/standard-way-of-creating-config-file-suitable-for-python-and-java-together\n\
and\n\
https://docs.python.org/2/library/configparser.html\n\
. (Websites accessed 13/8/2016).')
print('option1 from Section1 =', opt1, '\n Option 2 from section 1 is', str(opt2), '\nand option 3 from section 1 is "'+opt3+'".')
input('Press ENTER to exit.')
来源:https://stackoverflow.com/questions/21766451/how-to-read-config-from-string-or-list