How to import a module given the full path? How to import a module given the full path? python python

How to import a module given the full path?


For Python 3.5+ use:

import importlib.utilspec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py")foo = importlib.util.module_from_spec(spec)spec.loader.exec_module(foo)foo.MyClass()

For Python 3.3 and 3.4 use:

from importlib.machinery import SourceFileLoaderfoo = SourceFileLoader("module.name", "/path/to/file.py").load_module()foo.MyClass()

(Although this has been deprecated in Python 3.4.)

For Python 2 use:

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

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

See also http://bugs.python.org/issue21436.


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.pysys.path.append('/foo/bar/mock-0.3.1')from testcase import TestCasefrom testutils import RunTestsfrom mock import Mock, sentinel, patch


To import your module, you need to add its directory to the environment variable, either temporarily or permanently.

Temporarily

import syssys.path.append("/path/to/my/modules/")import my_module

Permanently

Adding the following line to your .bashrc (or alternative) file in Linuxand excecute source ~/.bashrc (or alternative) in the terminal:

export PYTHONPATH="${PYTHONPATH}:/path/to/my/modules/"

Credit/Source: saarrrr, another Stack Exchange question