问题:
是否有模块或推荐方法从 Python 源文件中获取所有显式 import 语句?
我目前的研究:
我尝试使用模块的这个 gem:modulefinder .我的问题是,这列出了源文件曾经使用过的所有模块,包括递归使用的所有隐式和隐式模块。
我正在寻找一种方法来获取源文件显式导入的导入,不是隐式/递归导入。
示例:
直接从文档中取出这个:
#bacon.py
import re, itertools
try:
import baconhameggs
except ImportError:
pass
try:
import guido.python.ham
except ImportError:
pass
现在是 modulefinder 代码:
from modulefinder import ModuleFinder
finder = ModuleFinder()
finder.run_script('bacon.py')
print 'Loaded modules:'
for name, mod in finder.modules.iteritems():
print '%s: ' % name,
print ','.join(mod.globalnames.keys()[:3])
print '-'*50
print 'Modules not imported:'
print '\n'.join(finder.badmodules.iterkeys())
输出:
Loaded modules:
_types:
copy_reg: _inverted_registry,_slotnames,__all__
sre_compile: isstring,_sre,_optimize_unicode
_sre:
sre_constants: REPEAT_ONE,makedict,AT_END_LINE
sys:
re: __module__,finditer,_expand
itertools:
__main__: re,itertools,baconhameggs
sre_parse: __getslice__,_PATTERNENDERS,SRE_FLAG_UNICODE
array:
types: __module__,IntType,TypeType
---------------------------------------------------
Modules not imported:
guido.python.ham
baconhameggs
我希望获得的输出:
Loaded modules:
re
itertools
guido.python.ham
baconhameggs
感谢您的建议。
请您参考如下方法:
#modulefinder.py
import filename
print dir(filename)
其中文件名是包含“显式”导入的模块。 不幸的是,这也会显示您的函数名称。
