views:

3346

answers:

9

How can I load a python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option.

+1  A: 

I believe you can use imp.find_module() and imp.load_module() to load the specified module. You'll need to split the module name off of the path, i.e. if you wanted to load "/home/mypath/mymodule.py" you'd need to do "imp.find_module('mymodule', '/home/mypath/')", but that should get the job done.

Matt
A: 

I believe you want this function from the standard library: http://docs.python.org/lib/module-imp.html#l2h-5362

+27  A: 
import imp

foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()

There are equivalent convenience functions for compiled Python files and DLLs.

Sebastian Rittau
If I knew the namespace - 'module.name' - I would already use `__import__`.
Sridhar Ratnakumar
Thank a lot for pointing me toward this dark corner of Python's standard library.
thomas
+1  A: 

You can use the

load_source(module_name, path_to_file)

method from imp module.

zuber
+3  A: 

http://code.activestate.com/recipes/223972/

A: 

You can also do something like this and add the directory that the config file is sitting in to the python load path, and then just do a normal import, assuming you know the name of the file in advance, in this case "config"

Messy but it works.

configfile = '~/config.py'

import os
import sys

sys.path.append(os.path.dirname(os.path.expanduser(configfile)))

import config
ctcherry
+3  A: 

Do you mean load or import?

You can manipulate the sys.path list specify the path to your module, then import your module. For example, given a module at:

/foo/bar.py

You could do:

import sys
sys.path[0:0] = '/foo' # puts the /foo directory at the start of your path
import bar
Wheat
Shouldn't the second import be "import bar"?
Daryl Spitzer
+1  A: 
def import_file(full_path_to_module):
    try:
        import os
        module_dir, module_file = os.path.split(full_path_to_module)
        module_name, module_ext = os.path.splitext(module_file)
        save_cwd = os.getcwd()
        os.chdir(module_dir)
        module_obj = __import__(module_name)
        module_obj.__file__ = full_path_to_module
        globals()[module_name] = module_obj
        os.chdir(save_cwd)
    except:
        raise ImportError

import_file('/home/somebody/somemodule.py')
Chris Calloway
+1  A: 

The advantage of adding a path to sys.path (over using imp) is that it simplifies things when importing more than one module from a single package. For example:

import sys
# the mock-0.3.1 dir contains testcase.py, testutils.py & mock.py
sys.path.append('/foo/bar/mock-0.3.1')

from testcase import TestCase
from testutils import RunTests
from mock import Mock, sentinel, patch
Daryl Spitzer