我正在編寫一個程序,通過它們導入的模塊對Python文件列表進行分類。因此,我需要掃描.py文件集合並返回它們導入哪些模塊的列表。舉個例子,如果我導入文件中的一個具有以下行:返回腳本中使用的導入Python模塊的列表?
import os
import sys, gtk
我想它返回:
["os", "sys", "gtk"]
我打了modulefinder寫道:
from modulefinder import ModuleFinder
finder = ModuleFinder()
finder.run_script('testscript.py')
print 'Loaded modules:'
for name, mod in finder.modules.iteritems():
print '%s ' % name,
但這不僅僅是返回腳本中使用的模塊。作爲其中僅僅有一個腳本的例子:
import os
print os.getenv('USERNAME')
模塊從ModuleFinder腳本返回的回報:
tokenize heapq __future__ copy_reg sre_compile _collections cStringIO _sre functools random cPickle __builtin__ subprocess cmd gc __main__ operator array select _heapq _threading_local abc _bisect posixpath _random os2emxpath tempfile errno pprint binascii token sre_constants re _abcoll collections ntpath threading opcode _struct _warnings math shlex fcntl genericpath stat string warnings UserDict inspect repr struct sys pwd imp getopt readline copy bdb types strop _functools keyword thread StringIO bisect pickle signal traceback difflib marshal linecache itertools dummy_thread posix doctest unittest time sre_parse os pdb dis
...而我只是希望它返回「操作系統」,因爲這是腳本中使用的模塊。
任何人都可以幫助我實現這個目標嗎?
UPDATE:我只是想澄清一下,我想這樣做,而不運行被分析的Python文件,只是掃描代碼。
是使用import語句手動添加的那些額外模塊中的任何一個嗎?如果不是的話,你能不能僅僅創建一個空模塊,運行你的模塊查找器,並通過從其他模塊的結果中刪除這些模塊來使用結果?即。 'modulefinder(some_module) - modulefinder(empty_module)'? – 2010-04-03 21:09:52