SafeConfigParser: sections and environment variables
<p>(<em>Using Python 3.4.3</em>)</p>

<p>I want to use environment variables in my config file and I read that I should use <code>SafeConfigParser</code> with <code>os.environ</code> as parameter to achieve it.</p>

<pre><code>[test]
mytest = %(HOME)s/.config/my_folder
</code></pre>

<p>Since I need to get all the options in a section, I am executing the following code:</p>

<pre><code>userConfig = SafeConfigParser(os.environ)
userConfig.read(mainConfigFile)
for section in userConfig.sections():
    for item in userConfig.options(section):
        print( "### " + section + " -&gt; " + item)
</code></pre>

<p>My result is not what I expected. As you can see below, it got not only the option I have in my section (<code>[test]\mytest</code>), but also all the environment variables:</p>

<pre class="lang-none prettyprint-override"><code>### test -&gt; mytest
### test -&gt; path
### test -&gt; lc_time
### test -&gt; xdg_runtime_dir
### test -&gt; vte_version
### test -&gt; gnome_keyring_control
### test -&gt; user
</code></pre>

<p>What am I doing wrong?</p>

<p>I want to be able to parse <code>[test]\mytest</code> as <code>/home/myuser/.config/my_folder</code> but don't want the <code>SafeConfigParser</code> adding all my environment variables to each one of its sections.</p>

<p>If I have understood your question and what you want to do correctly, you can avoid the problem by  <strong><em>not</em></strong> supplying <code>os.environ</code> as parameter to <code>SafeConfigParser</code>. Instead use it as the <code>vars</code> keyword argument's value when you actually retrieve values using the <code>get()</code> method.</p>

<p>This works because it avoids creating a <em>default</em> section from all your environment variables, but allows their values to be used when referenced for interpolation/expansion purposes.</p>

<pre><code>userConfig = SafeConfigParser()
userConfig.read(mainConfigFile)
for section in userConfig.sections():
    for item in userConfig.options(section):
        value = userConfig.get(section, item, vars=os.environ)  # use it here
        print('### [{}] -&gt; {}: {!r}'.format(section, item, value))
</code></pre>

python environment-variables python-3.4 configparser