程式扎記: [ Python 常見問題 ] How to list imported modules?

標籤

2015年8月18日 星期二

[ Python 常見問題 ] How to list imported modules?

Source From Here 
Question 
How to enumerate all imported modules? E.g. I would like to get ['os', 'sys'] for from this code: 
  1. import os  
  2. import sys  
How-To 
You can leverage Python std library sys.modules
  1. # -*- coding: utf-8 -*-    
  2. import sys  
  3. import os  
  4.   
  5. imported_modules = sys.modules.keys()  
  6. print "Total {0} modules being imported:".format(len(imported_modules))  
  7. for m in ["os""sys""struct"]:  
  8.     print "\tIncluding {0}? {1}".format(m, m in imported_modules)​​​  
Execution Result: 
Total 48 modules being imported:
Including os? True
Including sys? True
Including struct? False

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: 
  1. # -*- coding: utf-8 -*-    
  2. import sys  
  3. import os  
  4. import types  
  5.   
  6. def imports():  
  7.     for name, val in globals().items():  
  8.         if isinstance(val, types.ModuleType):  
  9.             yield val.__name__  
  10.   
  11. for m in imports():  
  12.     print "{0}".format(m)  
Execution Result 
__builtin__
sys
os
types

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 aliasyield name instead if you want the alias.

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!