I\'m writing a Python application that takes as a command as an argument, for example:
$ python myapp.py command1
I want the application to
Nowadays you should use importlib.
The docs actually provide a recipe for that, and it goes like:
import sys
import importlib.util
file_path = 'pluginX.py'
module_name = 'pluginX'
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
# check if it's all there..
def bla(mod):
print(dir(mod))
bla(module)
This way you can access the members (e.g, a function "hello
") from your module pluginX.py
-- in this snippet being called module
-- under its namespace; E.g, module.hello()
.
If you want to import the members (e.g, "hello
") you can include module
/pluginX
in the in-memory list of modules:
sys.modules[module_name] = module
from pluginX import hello
hello()
Importing a package (e.g., pluginX/__init__.py
) under your current dir is actually straightforward:
import importlib
pkg = importlib.import_module('pluginX')
# check if it's all there..
def bla(mod):
print(dir(mod))
bla(pkg)