how to call def from another .py in different folder
<p>I have following structure:
utils_dir has generator.py file which has 3 defs.</p>

<p>I have test.py in inline_dir. And I am trying to use defs from generator.py in test.py. </p>

<p>inline_dir and utils_dir are in different folders.
How can I achieve it to use defs?</p>

<p>Tried with creating <code>_init_.py</code> and then calling <code>import generator</code>. - Not worked.
Tried <code>from utils import generator</code> - Not worked</p>

<p><code>Dir structure</code></p>

<p><code>
Support_dir
âââ dir_A
â   âââ dir_aa
â   âââ----- main.py   [Want to use a and b from generator.py]
âââ utils
    |
    âââ generator.py
             |
             |___ def a
             |___ def b
</code></p>

<p>This is a kind of a python path problem. When you import, python will search current directory and default system path directory. Since utils_dir is not your current work directory (when import, you work in inline_dir), nor in default python search system path, that is why the import not work.</p>

<p>A simple way to solve is </p>

<p>a). First make utils_dir as python package: simply add <strong>init</strong>.py in the directory.</p>

<p>b). Then, add path of parent folder of utils_dir to PYTHONPATH environment variable.</p>

<pre><code>export PYTHONPATH=/home/user/parent_of_utils_dir:$PYTHONPATH
</code></pre>

<p>You can add this line into your .bashrc to make it available all the time.</p>

<p>c). In your test.py, import the function</p>

<pre><code>from utils import generator
</code></pre>

<p>or</p>

<pre><code>import utils.generator
</code></pre>

<p>A more python development way is to use setuptools, and write python script setup.py, which will solve dependency problem. And then you can use</p>

<pre><code>python setup.py develop
</code></pre>

<p>to use in develop mode.</p>

<p>Check more python package development guide at <a href="https://packaging.python.org/" rel="nofollow">https://packaging.python.org/</a></p>

<p>Hope this will help you.</p>

python