Please enable Javascript to view the contents

动态导包和已导入的模块

 ·  ☕ 1 分钟  ·  🦊 Herschel

How to list imported modules

  • How to enumerate all imported modules?
  • E.g. I would like to get [‘os’,‘sys’] from this code:
1
2
import sys
import os

Answer liked most

  • 所有加载模块都会出现在sys.moudles
1
2
import sys
sys.moudles.keys()
  • An approximation of getting all imports for the current module only would be to inspect globals() for modules:
1
2
3
4
5
6
7
8
9
import types

def imports():
    for name, val in globals.items():
        if isinstance(val, types.MoudleType):
            yield val.__name__

imported_moudles = [i for i in imports()]
print(imported_moudles)
  • This won’t return local imports, or non-moudle imports like from x import y. Note that this returns val.__name__ so you get the original module name if you used import moudle as alias; yield name instead if you want the alias.

dynamically import

  • 以下两种方式均可将变量或者包名的字符串传入,动态加载模块。
    1. exec()
    2. __import__()
分享

Herschel
作者
Herschel
coder, may be a gopher