python importing file on virtual environment
<p>I am writing a web app using python3, venv and c9.io PAAS. I have the following structure of my code:</p>

<pre><code>batch_runner.py
logic/
    __init__.py
    parsers/
        __init__.py
        time_parser.py
        abstract_parser.py
</code></pre>

<p>here <code>batch_runner</code> imports <code>abstract_parser</code>, which, in it turn, import from time_parser. everything was installed and runs with venv activated.</p>

<p>To be specific, <code>batch_runner.py</code> contains:</p>

<pre><code>from logic.parsers import abstract
from sys import argv

url = argv[1]
a = abstract(url)
</code></pre>

<p><code>logic/__init__.py</code> is empty. <code>logic/parsers/__init__.py</code> contains:</p>

<pre><code>from abstract_parser import abstract
from time_parser import _timeInfo
</code></pre>

<p>If I go to <code>logic</code> and run <code>python abstract_parser.py</code> directly, everything works as expected. However, if I go one level up, and run <code>python batch_runner.py</code>, it is able to import <code>abstract_parser</code>, but it can't find <code>time_parser</code> which is called from <code>abstract_parser</code>, throwing <code>ImportError: No module named 'abstract'</code></p>

<p>Do read about importing from the <a href="https://docs.python.org/2/tutorial/modules.html#packages" rel="nofollow">python documentation</a> on modules.</p>

<p>In this case, one possible solution is to use relative imports inside your package:</p>

<p>That is, in <code>logic/parsers/__init__.py</code>, use:</p>

<pre><code>from .abstract_parser import abstract
from .time_parser import _timeInfo
</code></pre>

<p>and in <code>abstract_parser.py</code>:</p>

<pre><code>from .time_parser import _timeInfo
</code></pre>

<p>This should let <code>parsers/__init__.py</code> find the <code>abstract_parser</code> module and the <code>time_parser</code> module.</p>

<p>The python import system has a surprising number of traps that you can fall into. <a href="http://python-notes.curiousefficiency.org/en/latest/python_concepts/import_traps.html" rel="nofollow">This blog post</a> by Nick Coghlan describes many of them, and I personally consider it a must-read if you're planning to develop a package.</p>

python python-venv c9.io