Search notes:

Python standard library: importlib

importlib

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')
Github repository about-python, path: /standard-library/importlib/import-from-arbitrary-path/dir-module/FooModule.py
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()
Github repository about-python, path: /standard-library/importlib/import-from-arbitrary-path/dir-script/import-from-arbitrary-path.py

See also

standard library

Index