packages = pkgutil.walk_packages(path='.') for importer, name, is_package in packages: mod = importlib.import_module(name) # do whatever you want with module now, it's been imported!
使用thesmuggler包
1 2 3 4 5 6 7 8 9 10
from thesmuggler import smuggle
# à la `import weapons` weapons = smuggle('weapons.py')
# à la `from contraband import drugs, alcohol` drugs, alcohol = smuggle('drugs', 'alcohol', source='contraband.py')
# à la `from contraband import drugs as dope, alcohol as booze` dope, booze = smuggle('drugs', 'alcohol', source='contraband.py')
dirname, basename = os.path.split(pyfilepath) # pyfilepath: '/my/path/mymodule.py' sys.path.append(dirname) # only directories should be added to PYTHONPATH module_name = os.path.splitext(basename)[0] # '/my/path/mymodule.py' --> 'mymodule' module = importlib.import_module(module_name) # name space of defined module (otherwise we would literally look for "module_name")
pkg = "mypkg" spec = importlib.machinery.PathFinder().find_spec(pkg, ["/path/to/mypkg-parent"]) mod = importlib.util.module_from_spec(spec) sys.modules[pkg] = mod # needed for exec_module to work spec.loader.exec_module(mod) sys.modules[pkg] = importlib.import_module(pkg)
defload_module(name, filename): # If the Loader finds the module name in this list it will use # module_name.__file__ instead so we need to delete it here if name in sys.modules: del sys.modules[name] loader = importlib.machinery.ExtensionFileLoader(name, filename) module = loader.load_module() locals()[name] = module globals()[name] = module