【发布时间】:2014-09-03 07:41:19
【问题描述】:
我正在尝试重新加载我编写的整个自定义模块包。
我在这里查看了another question,但它看起来不适用于我的情况。
modules/__init__.py
# based on info from https://stackoverflow.com/questions/1057431/loading-all-modules-in-a-folder-in-python
import os
for module in os.listdir(os.path.dirname(__file__)):
if module[0:8] != '__init__' and module[-3:] == '.py':
if module in dir(os.path.dirname(__file__)):
reload(module)
else:
__import__(module[:-3], locals(), globals())
del module
del os
加载模块:
import modules
def loadModule(self, moduleName):
"""
Load the module with the give name
i.e. "admin" would load modules/admin.py
Args:
moduleName (str): name of the module (admin would load the admin.py file)
Returns:
boolean: success or failure of load
Raises:
None
"""
retLoadedCorrectly = False
# reload everything to dynamically pick up new stuff
reload(modules)
# grab the module
try:
m = getattr(modules, moduleName)
# save it
self.loadedModules[m.commandName] = {'module': moduleName, 'admin': m.adminOnly, 'version': m.version}
# Yay it loaded :)
retLoadedCorrectly = True
# log it
self.log('Loaded module: {0}, {1}, {2}, {3}'.format(moduleName, m.commandName, m.adminOnly, m.version))
except AttributeError:
self.log('Failed to load module: {0}'.format(moduleName), level='WARNING')
return retLoadedCorrectly
如果我调用loadMudule("example"),它将按预期加载和运行。然后如果我更改示例,然后再次调用 loadModules 方法,则它不会接受更改。
我读到了importlib,但看起来它只是 python 3,我使用的是 python 2.7.6
如果这是一种不好的做法,请务必为我指明一个更好的方向!
【问题讨论】:
-
importlib在 python 2 中 -
它似乎只有
import_module,我认为这只是__import__的一个包裹
标签: python python-2.7 python-module