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

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

For Python 3.5+ use:

import importlib.util
spec = 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 SourceFileLoader

foo = 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 imp

foo = 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.py
sys.path.append(/foo/bar/mock-0.3.1)

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

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

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

Temporarily

import sys
sys.path.append(/path/to/my/modules/)
import my_module

Permanently

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

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

Credit/Source: saarrrr, another Stack Exchange question

Leave a Reply

Your email address will not be published.