繁体   English   中英

ConfigParser - 获取整个部分作为字典并设置值

[英]ConfigParser - get entire section as dict and set values

我想要做的(理想)是使用with用字典一次设置的参数一整节。 经过一些试验,我想出了以下代码,它引发了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 文件:

[Settings]
username = ''

回溯:

Traceback (most recent call last):
  File "test.py", line 9, in <module>
    with dict(config.items('Settings')) as c:
AttributeError: __enter__

我觉得我在这里使用configparser错误的,但我想写一些漂亮的代码来设置config.ini参数。

你不能用一个字典, with ,因为字典不是一个上下文管理器。

with dict() as d:
    print d

输出:

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

对象必须定义__enter____exit__才能用作上下文管理器。

文档: http : //book.pythontips.com/en/latest/context_managers.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM