2011-03-07 243 views

回答

4

下面是它增加了一些精度的扭曲,如果你发现你经常检查的杂项代码依赖性,这可能是有用的:由被分析的代码执行

  • 仅捕捉import语句。
  • 自动排除所有系统加载的模块,因此您不必去除它。
  • 还报告从每个模块导入的符号。

代码:

import __builtin__ 
import collections 
import sys 

IN_USE = collections.defaultdict(set) 
_IMPORT = __builtin__.__import__ 

def _myimport(name, globs=None, locs=None, fromlist=None, level=-1): 
    global IN_USE 
    if fromlist is None: 
     fromlist = [] 
    IN_USE[name].update(fromlist) 
    return _IMPORT(name, globs, locs, fromlist, level) 

# monkey-patch __import__ 
setattr(__builtin__, '__import__', _myimport) 

# import and run the target project here and run the routine 
import foobar 
foobar.do_something() 

# when it finishes running, dump the imports 
print 'modules and symbols imported by "foobar":' 
for key in sorted(IN_USE.keys()): 
    print key 
    for name in sorted(IN_USE[key]): 
     print ' ', name 

foobar模块:

import byteplay 
import cjson 

def _other(): 
    from os import path 
    from sys import modules 

def do_something(): 
    import hashlib 
    import lxml 
    _other() 

输出:

modules and symbols imported by "foobar": 
_hashlib 
array 
    array 
byteplay 
cStringIO 
    StringIO 
cjson 
dis 
    findlabels 
foobar 
hashlib 
itertools 
lxml 
opcode 
    * 
    __all__ 
operator 
os 
    path 
sys 
    modules 
types 
warnings 
0

绝对!如果您使用的是UNIX或Linux shell,则可以使用grepawk的简单组合;基本上,所有你想要做的就是搜索包含“import”关键字的行。然而,如果你在任何环境下工作,你可以写一个小的Python脚本来为你做搜索(不要忘记字符串被视为不可变的序列,所以你可以做一些类似于if "import" in line: ...

该一个粘点,将是那些import ED模块以它们的包名称(想到的是PIL模块,在Ubuntu它是由python-imaging包中提供的第一个)相关联。

0

Python代码可以导入模块使用运行时构建的字符串,所以唯一可靠的方法就是运行代码。真实世界例如:当您使用SQLAlchemy的dbconnect打开数据库时,该库将根据数据库字符串的内容加载一个或多个db-api模块。

如果你愿意来运行代码,这里是一个比较简单的方法通过检查sys.modules要做到这一点,当它完成:

>>> from sys import modules 
>>> import codeofinterest 
>>> execute_code_of_interest() 
>>> print modules 
[ long, list, of, loaded, modules ] 

在这里,你应该记住,这可能理论上如果execute_code_of_interest()修改为sys.modules则失败,但我认为这在生产代码中非常罕见。

+1

一个好方法做到这一点是记住在已加载的模块的列表中程序开始,然后将其与最后加载的列表进行比较。您可以使用集合并减去它们,例如'set(modules) - set(modules_at_start)'。 – kindall 2011-03-07 03:35:24

+0

是的,他说:) – phooji 2011-03-07 03:38:06