tags:

views:

344

answers:

2

How can I convert the result of a ConfigParser.items('section') to a dictionary to format a string like here:

import ConfigParser

config = ConfigParser.ConfigParser()
config.read('conf.ini')

connection_string = "dbname='%(dbname)s' user='%(dbuser)s' host='%(host)s' password='%(password)s' port='%(port)s'"

print connection_string % config.items('db')
+3  A: 

Have you tried

print connection_string % dict(config.items('db'))

?

Ian Clelland
+2  A: 

This is actually already done for you in config._sections. Example:

$ cat test.ini
[First Section]
var = value
key = item

[Second Section]
othervar = othervalue
otherkey = otheritem

And then:

>>> 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: My solution to the same problem was downvoted so I'll further illustrate how my answer does the same thing without having to pass the section thru dict(), because config._sections is provided by the module for you already.

Example test.ini:

[db]
dbname = testdb
dbuser = test_user
host   = localhost
password = abc123
port   = 3306

Magic happening:

>>> 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'"

So this solution is not wrong, and it actually requires one less step. Thanks for stopping by!

jathanism
This is wrong ways, since it doesn't account defaults and variables are not interpolated.
Denis Otkidach
How is this "wrong ways" if it gives the same result?
jathanism