编程语言
首页 > 编程语言> > python-生成导入图

python-生成导入图

作者:互联网

我接近最终目标,那就是在模块和其他导入的模块之间生成一个漂亮的图形.

例如,如果x从y和z导入,而y从t和v导入,我希望具有:

x -> y, z
y -> t, v

现在,我已经定义了如下所示的导入钩子,但是在一个简单的文件上运行它并没有得到我期望的结果:

python study_imports.py CollectImports simple.py

('study_imports.py', 'study_imports')

实际上simple.py是从study_imports导入的.
问题是我想查看“ simple.py”而不是“ study_imports.py”,有没有办法获取实际导入其他模块的文件的路径?

class CollectImports(object):
    """
    Import hook, adds each import request to the loaded set and dumps
    them to file
    """

    def __init__(self, output_file):
        self.loaded = set()
        self.output_file = output_file

    def __str__(self):
        return str(self.loaded)

    def cleanup(self):
        """Dump the loaded set to file
        """
        dumped_str = '\n'.join(x for x in self.loaded)
        open(self.output_file, 'w').write(dumped_str)

    def find_module(self, module_name, package=None):
        #TODO: try to find the name of the package which is actually
        #importing something else, and how it's doing it
        #use a defualtdict with empty sets as the storage for this job
        entry = (__file__, module_name)
        self.loaded.add(str(entry))

解决方法:

也许使用inspect模块.

模块a.py

import inspect

print inspect.stack()

模块b.py

import a

当运行b.py时,我得到了:

[
   (<frame object at 0x28a9b70>, '/path/a.py', 5, '<module>', ['print inspect.stack()\n'], 0),
   (<frame object at 0x28a9660>, 'b.py', 2, '<module>', ['import to_import\n'], 0)
]

看起来第二帧包含您需要的内容.

标签:import,introspection,python
来源: https://codeday.me/bug/20191202/2085524.html