Questo è già stato fatto per voi in config._sections
. Esempio:
$ cat test.ini
[First Section]
var = value
key = item
[Second Section]
othervar = othervalue
otherkey = otheritem
E poi:
>>> from ConfigParser import ConfigParser
>>> config = ConfigParser()
>>> config.read('test.ini')
>>> config._sections
{'First Section': {'var': 'value', '__name__': 'First Section', 'key': 'item'}, 'Second Section': {'__name__': 'Second Section', 'otherkey': 'otheritem', 'othervar': 'othervalue'}}
>>> config._sections['First Section']
{'var': 'value', '__name__': 'First Section', 'key': 'item'}
Edit: La mia soluzione per lo stesso problema è stato downvoted quindi dovrò ulteriormente illustrare come la mia risposta fa la stessa cosa, senza dover passare alla sezione attraverso dict()
, perché config._sections
è fornito dal modulo per voi già.
Esempio Test.ini:
[db]
dbname = testdb
dbuser = test_user
host = localhost
password = abc123
port = 3306
magia accada:
>>> config.read('test.ini')
['test.ini']
>>> config._sections
{'db': {'dbname': 'testdb', 'host': 'localhost', 'dbuser': 'test_user', '__name__': 'db', 'password': 'abc123', 'port': '3306'}}
>>> connection_string = "dbname='%(dbname)s' user='%(dbuser)s' host='%(host)s' password='%(password)s' port='%(port)s'"
>>> connection_string % config._sections['db']
"dbname='testdb' user='test_user' host='localhost' password='abc123' port='3306'"
Quindi questa soluzione è non sbagliato, e richiede in realtà uno di meno passo. Grazie per esserti fermato!
Attenzione a usare _sections: questa variabile non è documentata, quindi non è garantito il funzionamento nelle future versioni di Python – Bertera
Questo è valido per python 2, ma se stai usando python 3 puoi semplicemente decomprimere la configurazione con subscript in formato(). "your {pattern}". Format (** config ['db']) – Hovis