python中模块的查找_如何查找依赖于Python中特定模块的模块列表

所以-这个答案“找到一个依赖于给定模块的模块列表”-而不是问题的最初措辞-我在上面回答了这个问题。

事实证明,这有点复杂:必须找到所有加载模块的依赖树,并为每个模块反转它,同时保留不会破坏事物的加载顺序。

#! /usr/bin/env python

# coding: utf-8

# Author: João S. O. Bueno

# Copyright (c) 2009 - Fundação CPqD

# License: LGPL V3.0

from types import ModuleType, FunctionType, ClassType

import sys

def find_dependent_modules():

"""gets a one level inversed module dependence tree"""

tree = {}

for module in sys.modules.values():

if module is None:

continue

tree[module] = set()

for attr_name in dir(module):

attr = getattr(module, attr_name)

if isinstance(attr, ModuleType):

tree[module].add(attr)

elif type(attr) in (FunctionType, ClassType):

tree[module].add(attr.__module__)

return tree

def get_reversed_first_level_tree(tree):

"""Creates a one level deep straight dependence tree"""

new_tree = {}

for module, dependencies in tree.items():

for dep_module in dependencies:

if dep_module is module:

continue

if not dep_module in new_tree:

new_tree[dep_module] = set([module])

else:

new_tree[dep_module].add(module)

return new_tree

def find_dependants_recurse(key, rev_tree, previous=None):

"""Given a one-level dependance tree dictionary,

recursively builds a non-repeating list of all dependant

modules

"""

if previous is None:

previous = set()

if not key in rev_tree:

return []

this_level_dependants = set(rev_tree[key])

next_level_dependants = set()

for dependant in this_level_dependants:

if dependant in previous:

continue

tmp_previous = previous.copy()

tmp_previous.add(dependant)

next_level_dependants.update(

find_dependants_recurse(dependant, rev_tree,

previous=tmp_previous,

))

# ensures reloading order on the final list

# by postponing the reload of modules in this level

# that also appear later on the tree

dependants = (list(this_level_dependants.difference(

next_level_dependants)) +

list(next_level_dependants))

return dependants

def get_reversed_tree():

"""

Yields a dictionary mapping all loaded modules to

lists of the tree of modules that depend on it, in an order

that can be used fore reloading

"""

tree = find_dependent_modules()

rev_tree = get_reversed_first_level_tree(tree)

compl_tree = {}

for module, dependant_modules in rev_tree.items():

compl_tree[module] = find_dependants_recurse(module, rev_tree)

return compl_tree

def reload_dependences(module):

"""

reloads given module and all modules that

depend on it, directly and otherwise.

"""

tree = get_reversed_tree()

reload(module)

for dependant in tree[module]:

reload(dependant)

这在我在这里做的所有测试中都很好,但我不反对滥用它。

但是为了在编辑了几行代码之后更新一个运行中的Zope2服务器,我想我自己也会使用它。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值