Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python -- import a module from a directory that's not a package

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

for Python 3.x

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()
like image 596
treecoder Avatar asked May 10 '12 12:05

treecoder


2 Answers

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')
like image 117
Daren Thomas Avatar answered Sep 19 '22 09:09

Daren Thomas


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
  1. add the file __init__.py into the dir1, dir2, dir3 ...
  2. Inside a package hierarchy, use two dots.

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?

like image 41
1943 Yonv Avatar answered Sep 20 '22 09:09

1943 Yonv