如何在 Python 模块中列出导入? [英] How to list imports within a Python module?

查看:52
本文介绍了如何在 Python 模块中列出导入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是获取代表特定模块中导入的模块对象列表,例如通过检查/反映.我可以获得导入的全局列表,但这并不能告诉我哪个模块正在使用哪些其他模块.

What I'm trying to do is get a list of module objects that represent the imports within a specific module, e.g. via inspection/reflection. I can get the global list of imports but this doesn't tell me which module is using which other modules.

明确地说,我指的是 Python 中的模块,而不是 PIP 安装的包.我正在寻找完全在 Python 2.7 中的代码以获取模块引用(比如 sys.modules['foo'])并返回该模块导入的 list 作为名称、路径或其他模块对象.(我现在真正想要的只是路径.)

To be clear, I'm talking about modules in Python, not packages as installed by PIP. I'm looking for code entirely in Python 2.7 to take a module reference (say sys.modules['foo']) and return a list of that module's imports as either name, path, or another module object. (All I actually want right now is the path.)

import sys
for module_name in sys.modules:
   print "Modules imported by %s are: ..." % (module_name,)

您将如何完成上述代码段以实际列出导入?

How would you complete the above snippet to actually list the imports?

推荐答案

您可以使用 modulefinder 来自标准库的包.

You can use the modulefinder package from the standard library.

from modulefinder import ModuleFinder

finder = ModuleFinder()
finder.run_script('my_script.py')

for name, mod in finder.modules.iteritems():
    print(name)

这篇关于如何在 Python 模块中列出导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆