Saturday 26 March 2016

python - 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.


Answer




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.



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...