如何解决Python依赖关系分析器库
| 我需要一种在运行时查找我的Python包的每个子模块的依赖关系的方法,以便我可以按正确的顺序对其进行初始化(请参阅此处的当前[EDIT:前]解决方案,该方法对好),所以起初我使用标准的Python模块modulefinder,但这太慢了(每个模块1-2秒)。 我的下一个选择是分析每个模块的所有全局变量,并从这些全局变量中找到每个子模块所依赖的子模块。 (这是我当前的解决方案。编辑:我现在有一个更好的解决方案-请参阅我的答案)。该算法比modulefinder快得多(每个模块花费<200ms),但是它仅适用于相对导入,而不是完全合格的导入样式,这是不可接受的。 因此,我需要的是: 替代Modulefinder的更快方法 替代算法 注意:我在每个模块的开头调用我的依赖性分析器,如下所示:# File my_package/module3.py
import my_package.module1 # Some misc. module
import my_package.module2 # Some other misc. module
import my_package.dependency_analyzer
my_package.dependency_analyzer.gendeps()
(以防万一对您有帮助。)
谢谢!
编辑:我现在有一个解决方案-请参阅我的答案。
解决方法
我想我有一个解决自己的问题的方法:)
这是上面讨论的dependency_analyzer模块的内容:
import sys
from sys import _getframe as getframe
import atexit
examined_modules = []
def gendeps():
\"\"\"Adds the calling module to the initialization queue.\"\"\"
# Get the calling module\'s name,and add it to the intialization queue
calling_module_name = getframe(1).f_globals[\'__name__\']
examined_modules.append(calling_module_name)
def init():
\"\"\"Initializes all examined modules in the correct order.\"\"\"
for module in examined_modules:
module = sys.modules[module]
if hasattr(module,\'init\'):
module.init()
if hasattr(module,\'deinit\'):
# So modules get de-initialized in the correct order,# as well
atexit.register(module.deinit)
现在,在每个模块的开头(在所有import语句之后-这都是至关重要的),放置了对gendeps的调用。该算法之所以有效,是因为每次导入模块都会执行对gendeps的调用。但是,由于所有导入语句都放置在您自己的模块中对gendeps的调用之前,因此,依赖性最小的模块首先放置在初始化队列中,而依赖性最大的模块最后放置在初始化队列中。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。