Search code examples
pythonpython-2.7dockerfig

How to import a directory with modules to Python path that is a symlink to original source from a subfolder?


I am trying to run docker containers child1 and child2. lets say we have:

UPDATED

|parent
|-----|child1/
             src_folder/
                       __init__.py
                       mod1.py
|-----|child2/
            __init__.py
            symlink_target_folder
            mody.py
            test1_dir/
                      smfile.py

I have done something like

ln -rs ~/parent/child1/src_folder ~/parent/child2/symlink_target_folder

In mody.py When I do,

from symlink_target_folder import mod1

it works;

but from test1_dir>smfile.py when I do

from .child2.symlink_target_folder import mod1

it throws back ImportError.

I want to know how could I access the same module from that directory ? Could exporting symlink_target_folder to PYTHONPATH someway work it out. I have done

export PYTHONPATH=$PYTHONPATH:/symlink_target_folder

such that ` I can do from mody.py

from symlink_target_folder.mod1 import SmFoo

but I dont think its due to PYTHONPATH. just that symlink_target_folder and mody.py are in same folder.

How do I solve this? What would be a better way to approach this problem? I did check this out


Solution

  • Here is how I solved this problem;

    Given

    |parent
    |-----|child1/
                 src_folder/
                           __init__.py
                           mod1.py
    |-----|child2/
                __init__.py
                symlink_target_folder
                mody.py
                test1_dir/
                          smfile.py
    

    i created somepth.pth under child2 file which has this:

    symlink_target_folder

    Then a simplepth.py under child2 script like this:

    import site
    import os
    
    site.addsitedir(os.path.dirname(__file__))
    

    When you run child2>simplepth.py it will add the dir where simplepth is and any .pth file which naturally points to /child1/srcFolder and import it to sys.path

    now you can simply do:

    import mod1

    which solves my problem.

    so if you only want to run test1_dir/smFile.py you could just add test1_dir 's parent directory and add it to site.addsitedir and then import mod1 and it will work.