Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3.4: How to import a module given the full path? [duplicate]

How can I load a Python module in Python 3.4 given its full path?

A similar question How to import a module given the full path? covers Python versions before 3.4, but the conclusion is that support in Python 3.4 is deprecated for the presented answers, so any solution for Python 3.4 is appreciated.

Note that this question is not a duplicate of Import abitrary python source file. (Python 3.3+), since answers for this also use loader.load_module() which is deprecated in Python 3.4, as said in answer, with details in Consider leaving importlib.abc.Loader.load_module(), and documentation in importlib.

So a supported solution for module import by full path in Python 3.4 is needed.

like image 814
EquipDev Avatar asked Dec 09 '14 14:12

EquipDev


People also ask

How do you import an absolute path in Python?

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 an entire 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.

Can we import a module twice?

The rules are quite simple: the same module is evaluated only once, in other words, the module-level scope is executed just once. If the module, once evaluated, is imported again, it's second evaluation is skipped and the resolved already exports are used.

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.


1 Answers

This should work for all python files, regardless of file extension:

import importlib.machinery  modulename = importlib.machinery.SourceFileLoader('modulename','/Path/To/module.py').load_module() 

This method was mentioned in the deprecation message in the imp.load_module documentation.

like image 158
Evil Genius Avatar answered Sep 28 '22 03:09

Evil Genius