Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is actually already done for you in <code>config._sections</code>. Example:</p> <pre><code>$ cat test.ini [First Section] var = value key = item [Second Section] othervar = othervalue otherkey = otheritem </code></pre> <p>And then:</p> <pre><code>&gt;&gt;&gt; from ConfigParser import ConfigParser &gt;&gt;&gt; config = ConfigParser() &gt;&gt;&gt; config.read('test.ini') &gt;&gt;&gt; config._sections {'First Section': {'var': 'value', '__name__': 'First Section', 'key': 'item'}, 'Second Section': {'__name__': 'Second Section', 'otherkey': 'otheritem', 'othervar': 'othervalue'}} &gt;&gt;&gt; config._sections['First Section'] {'var': 'value', '__name__': 'First Section', 'key': 'item'} </code></pre> <p><strong>Edit:</strong> 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 <code>dict()</code>, because <code>config._sections</code> is <em>provided by the module for you already</em>.</p> <p><strong>Example test.ini:</strong></p> <pre><code>[db] dbname = testdb dbuser = test_user host = localhost password = abc123 port = 3306 </code></pre> <p>Magic happening:</p> <pre><code>&gt;&gt;&gt; config.read('test.ini') ['test.ini'] &gt;&gt;&gt; config._sections {'db': {'dbname': 'testdb', 'host': 'localhost', 'dbuser': 'test_user', '__name__': 'db', 'password': 'abc123', 'port': '3306'}} &gt;&gt;&gt; connection_string = "dbname='%(dbname)s' user='%(dbuser)s' host='%(host)s' password='%(password)s' port='%(port)s'" &gt;&gt;&gt; connection_string % config._sections['db'] "dbname='testdb' user='test_user' host='localhost' password='abc123' port='3306'" </code></pre> <p>So this solution is <strong>not</strong> wrong, and it actually requires one less step. Thanks for stopping by!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload