2011-03-07 242 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