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.
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.
I believe you want this function from the standard library: http://docs.python.org/lib/module-imp.html#l2h-5362
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.
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
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
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')
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