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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With