I have a directory structure like this...
dir/
build.py
dir2
dir3/
packages.py
Now the build.py
needs packages.py
-- and note that dir2
is not a package.
So what's the best way to get packages.py
loaded into build.py
(the directory structure can't be changed)
EDIT
The sys.path.append
solution seems good -- but there is one thing -- I need to use the packages.py
file rarely -- and keeping a sys.path
that includes a directory that is used rarely, but is at the front -- is that the best thing?
EDIT II
I think the imp
solution is best.
import imp
packages = imp.load_source('packages', '/path/to/packages.py')
EDIT III
Note that imp.load_source
and some other function have been deprecated. So you should use the imp.load_module
today.
fp, pathname, description = imp.find_module('packages', '/path/to/packages.py')
try:
mod = imp.load_module('packages', fp, pathname, description)
finally:
# since we may exit via an exception, close fp explicitly
if fp:
fp.close()
You could do:
sys.path.append('./dir2/dir3')
import packages
Or better yet:
sys.path.append(os.path.join(os.path.dirname(__file__), 'dir2/dir3'))
import packages
Or (taken from here: How to import a module given the full path?)
import imp
packages = imp.load_source('packages', '/path/to/packages.py')
Would the 'one right way' to do be the third ? - avoids messing directly with sys.path
I meet the same problems, and I solve it.
dir/
build.py
dir2
dir3/
packages.py
__init__.py
into the dir1, dir2, dir3 ...
bulid.py
want to import packages.py
, write in bulid.py:
import ..dir2.dir3.packages
from ..dir2.dir3.packages import function
https://docs.python.org/2/whatsnew/2.5.html#pep-328-absolute-and-relative-imports
Importing modules from parent folder
How to import a Python class that is in a directory above?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With