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.

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...