0

I would like to import modules from subdirectories in an easy way:

I would like to call all the functions in the app.py

.
├── app.py
└── testsubdir
    └── testsubsubdir
        ├── utils.py
testsubdir2
└── testsubsubdir2
    ├── utils2.py

To do this I use now:

sys.path.append('/home/www/testsubdir/testsubsubdir')
sys.path.append('/home/www/testsubdir2/testsubsubdir2')
from utils import <some_function>
from utils2 import <some_function>
  1. Is there a way to get /home/www as main path of the python calling script, so I don't need to write it every time. Something like this? sys.path.append('$MAINPATH.'/testsubdir2/testsubsubdir2')
  2. Is there a way to tell put all the subdirectories from the root of the project /home/www to the sys.path, so they are used to include libs?
Mutatos
  • 1,675
  • 4
  • 25
  • 55

1 Answers1

0

You need __init__.py files in each directory to help Python recognise that these are packages and directories of modules. You should not be modifying sys.path like this. See, for example, the docs for modules.

For the "sibling" case, you might be able to use sys.path.append(path) (or sys.path.insert(0, path), but it's not a very nice solution. For better alternatives, I would refer to this monster post.

So for your questions 1, you could (with the ugly hack) do os.path.append(os.path.dirname(os.path[0])).

ades
  • 227
  • 2
  • 14