簡體   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