Question
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.
How-To
Consider you have a python module under C:/tmp/test.py:
- def add(x, y):
- return x + y
- class Add:
- def __init__(self, x):
- self.x = x;
- def __call__(self, y):
- return self.x + y
- In [1]: import importlib.util
- In [2]: spec = importlib.util.spec_from_file_location('test.add', "C:/tmp/test.py")
- In [3]: spec.__class__
- Out[3]: _frozen_importlib.ModuleSpec
- In [4]: foo = importlib.util.module_from_spec(spec)
- In [5]: foo.__class__
- Out[5]: module
- In [7]: spec.loader.exec_module(foo)
- In [8]: foo.add(1, 2)
- Out[8]: 3
- In [10]: a = foo.Add(2)
- In [12]: a(3)
- Out[12]: 5
- from importlib.machinery import SourceFileLoader
- foo = SourceFileLoader('test.add', "C:/tmp/test.py").load_module()
- foo.add(1, 2) # Output 3
- import imp
- foo = imp.load_source('test.add', "C:/tmp/test.py")
- foo.add(1, 2) # Output 3
See also. http://bugs.python.org/issue21436.
Supplement
* FAQ - How to import other Python files?
沒有留言:
張貼留言