Question
How to enumerate all imported modules? E.g. I would like to get ['os', 'sys'] for from this code:
- import os
- import sys
You can leverage Python std library sys.modules:
- # -*- coding: utf-8 -*-
- import sys
- import os
- imported_modules = sys.modules.keys()
- print "Total {0} modules being imported:".format(len(imported_modules))
- for m in ["os", "sys", "struct"]:
- print "\tIncluding {0}? {1}".format(m, m in imported_modules)
An approximation of getting all imports for the current module only would be to inspect globals() (Return a dictionary representing the current global symbol table. This is always the dictionary of the current module) for modules:
- # -*- coding: utf-8 -*-
- import sys
- import os
- import types
- def imports():
- for name, val in globals().items():
- if isinstance(val, types.ModuleType):
- yield val.__name__
- for m in imports():
- print "{0}".format(m)
This won't return local imports, or non-module imports like from x import y. Note that this returns val.__name__ so you get the original module name if you usedimport module as alias; yield name instead if you want the alias.
沒有留言:
張貼留言