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>
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.