简体   繁体   中英

Import modules from sub directories - python

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?

For a relative import, you can just do from testsubdir.testsubsubdir import utils .

For the "sibling" case, it's a bit more tricky. You can 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])) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM