Python 从源文件获取显式导入 问题:
是否有一个模块或推荐的方法可以从Python源文件获取所有显式的Python 从源文件获取显式导入 问题:,python,python-import,python-internals,Python,Python Import,Python Internals,是否有一个模块或推荐的方法可以从Python源文件获取所有显式的import语句 到目前为止,我的研究: 我尝试使用这个gem模块:。我的例子中的问题是,它列出了源文件曾经使用过的所有模块,包括递归使用的所有隐式和隐含模块 我正在寻找一种方法,只获取源文件显式导入的导入,而不是隐式/递归导入 例子: 从文档中直接取出这个: #bacon.py import re, itertools try: import baconhameggs except ImportError: pa
import
语句
到目前为止,我的研究:
我尝试使用这个gem模块:。我的例子中的问题是,它列出了源文件曾经使用过的所有模块,包括递归使用的所有隐式和隐含模块
我正在寻找一种方法,只获取源文件显式导入的导入,而不是隐式/递归导入
例子:
从文档中直接取出这个:
#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
我希望获得的输出:
谢谢你的建议
#modulefinder.py
import filename
print dir(filename)
其中filename是包含“显式”导入的模块。
不幸的是,这也会显示您的函数名。您不能用正则表达式来实现吗?您是否关心导入内容的更黑客的方法?(例如,
\uuuuuuuuuuuuuuu导入
)您阅读了吗?我想这和你问的是一样的。@thefourtheye我把它作为最后的手段。@katrielex这些源文件将用于使用各种类型的导入语句,而不仅仅是\uuuuuuu import\uuu
谢谢。这是一种简单的方法,我完全没有注意到dir
也列出了导入的模块。很好。但是,我可能必须进入返回的列表并测试模块的项。使用此方法,我希望避免的另一个风险是需要首先导入模块。
#modulefinder.py
import filename
print dir(filename)