简体   繁体   English

如何在Python模块中列出导入?

[英]How to list imports within a Python module?

What I'm trying to do is get a list of module objects that represent the imports within a specific module, eg via inspection/reflection. 我想要做的是获取一个模块对象列表,这些对象代表特定模块内的导入,例如通过检查/反射。 I can get the global list of imports but this doesn't tell me which module is using which other modules. 我可以获得导入的全局列表,但这并不能告诉我哪个模块正在使用其他模块。

To be clear, I'm talking about modules in Python, not packages as installed by PIP. 明确地说,我说的 Python中的模块,而不是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. 我正在寻找完全在Python 2.7中的代码以获取模块引用(例如sys.modules['foo'] ),并以名称,路径或另一个模块对象的形式返回该模块导入的list (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? 您如何完成以上代码片段以实际列出进口商品?

You can use the modulefinder package from the standard library. 您可以使用标准库中的modulefinder软件包。

from modulefinder import ModuleFinder

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM