Importing a module from an arbitrary path
The
module to be imported is located in an arbitary directory, for example in
../dir-module
. The name of the module is
FooModule.py
. It has only one function:
print_something()
.
def print_something():
print('something')
The script that wants to import this module uses importlib.util
to locate and import the module:
#!/usr/bin/python
import importlib.util
spec = importlib.util.spec_from_file_location('What is this argument for????', '../dir-module/FooModule.py')
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
foo.print_something()