Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import a module given the full path?

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.

like image 298
derfred Avatar asked Sep 15 '08 22:09

derfred


People also ask

How do I import a module from a specific path?

append() Function. This is the easiest way to import a Python module by adding the module path to the path variable. The path variable contains the directories Python interpreter looks in for finding modules that were imported in the source files.

How do I import a whole module?

You need to use the import keyword along with the desired module name. When interpreter comes across an import statement, it imports the module to your current program. You can use the functions inside a module by using a dot(.) operator along with the module name.

How do I get the full path in Python?

Use abspath() to Get the Absolute Path in Pythonpath property. To get the absolute path using this module, call path. abspath() with the given path to get the absolute path. The output of the abspath() function will return a string value of the absolute path relative to the current working directory.

How do I set the path of a Python module?

To make sure Python can always find the module.py , you need to: Place module.py in the folder where the program will execute. Include the folder that contains the module.py in the PYTHONPATH environment variable. Or you can place the module.py in one of the folders included in the PYTHONPATH variable.


2 Answers

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 
like image 28
Daryl Spitzer Avatar answered Sep 27 '22 22:09

Daryl Spitzer


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.

like image 164
Sebastian Rittau Avatar answered Sep 28 '22 00:09

Sebastian Rittau