Adding and reading a config.ini file inside python package
<p>I am writing my first python package which I want to upload on PyPI. I structured my code based on this <a href="https://gehrcke.de/2014/02/distributing-a-python-command-line-application/" rel="noreferrer">blog post</a>.</p>

<p>I want to store user setting in a config.ini file. Read it once(every time the package is run) in separate python module in same package and save user setting in global variables of that module. Later import those in other modules.</p>

<p>To recreate the error I just edited few lines of code, in the template described in the blog post. (Please refer to it since it would take too much typing to recreate entire thing here in question.)</p>

<p>The only difference is that my <code>stuff.py</code> reads from config file like this:</p>

<pre><code>from ConfigParser import SafeConfigParser

config = SafeConfigParser()
config.read('config.ini')

TEST_KEY = config.get('main', 'test_key')
</code></pre>

<p>Here are the contents of <code>config.ini</code> (placed in same dir as <code>stuff.py</code>):</p>

<pre><code>[main]
test_key=value
</code></pre>

<p>And my <code>bootstrap.py</code> just imports and print the <code>TEST_KEY</code></p>

<pre><code>from .stuff import TEST_KEY

def main():
    print(TEST_KEY)
</code></pre>

<p>But on executing the package, the import fails give this error</p>

<pre><code>Traceback (most recent call last):
    File "D:\Coding\bootstrap\bootstrap-runner.py", line 8, in &lt;module&gt;
    from bootstrap.bootstrap import main
    File "D:\Coding\bootstrap\bootstrap\bootstrap.py", line 11, in &lt;module&gt;
    from .stuff import TEST_KEY
    File "D:\Coding\bootstrap\bootstrap\stuff.py", line 14, in &lt;module&gt;
    TEST_KEY = config.get('main', 'test_key')
    File "C:\Python27\Lib\ConfigParser.py", line 607, in get
    raise NoSectionError(section)
ConfigParser.NoSectionError: No section: 'main'
</code></pre>

<p>Import keeps giving <strong>ConfigParser.NoSectionError</strong>, but if you build/run only stuff.py(I use sublime3), the module gives no errors and printing <code>TEST_KEY</code> gives <code>value</code> as output.</p>

<p>Also, this method of import does work when I just use 3 files(config, stuff, main) in a dir and just execute the main as a script. But there I had to import it like this</p>

<pre><code>from stuff import TEST_KEY
</code></pre>

<p>I'm just using the explicit relative imports as described in that post but don't have enough understanding of those. I guess the error is due to project structure and import, since running <code>stuff.py</code> as standalone script raises no <code>ConfigParser.NoSectionError</code>.</p>

<p>Other method to read the config file once and then use data in other modules will be really helpful as well. </p>