[英]ConfigParser - get entire section as dict and set values
What I'd like to do (ideally) is use with
with a dictionary to set an entire section of parameters at once.我想要做的(理想)是使用
with
用字典一次设置的参数一整节。 After some experimenting I came up with the following code, which raises AttributeError
:经过一些试验,我想出了以下代码,它引发了
AttributeError
:
import configparser
import os
CONFIG_PATH = os.path.abspath(os.path.dirname(__file__)) + '/config.ini'
config = configparser.ConfigParser()
assert open(CONFIG_PATH)
config.read(CONFIG_PATH)
with dict(config.items('Settings')) as c:
c['username'] = input('Enter username: ')
config.ini file: config.ini 文件:
[Settings]
username = ''
The traceback:回溯:
Traceback (most recent call last):
File "test.py", line 9, in <module>
with dict(config.items('Settings')) as c:
AttributeError: __enter__
I feel like I'm using configparser
wrong here, but I'd like to write some beautiful code to set config.ini
parameters.我觉得我在这里使用
configparser
错误的,但我想写一些漂亮的代码来设置config.ini
参数。
You can't use a dictionary with with
because a dict is not a context manager.你不能用一个字典,
with
,因为字典不是一个上下文管理器。
with dict() as d:
print d
output:输出:
Traceback (most recent call last):
File "Main.py", line 6, in <module>
with dict() as d:
AttributeError: __exit__
https://paiza.io/projects/aPGRmOEmydbJL2ZeRtF-3A?language=python https://paiza.io/projects/aPGRmOEmydbJL2ZeRtF-3A?language=python
An object must define __enter__
and __exit__
in order to be used as a context manager.对象必须定义
__enter__
和__exit__
才能用作上下文管理器。
documentation: http://book.pythontips.com/en/latest/context_managers.html文档: http : //book.pythontips.com/en/latest/context_managers.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.