我有一个庞大的python模块库。有时,在导入模块时,我看到正在导入意外模块。为此,我一直在使用python -v
来查看正在导入的模块。从联机帮助页:
-v Print a message each time a module is initialized, showing the place
(filename or built-in module) from which it is loaded. When given twice,
print a message for each file that is checked for when searching for a
module. Also provides information on module cleanup at exit.
嗯,事实并非如此。例如:
import portalmq # directory /home/blahblah/python_modules/portalmq
# /home/blahblah/python_modules/portalmq/__init__.pyc matches /home/blahblah/python_modules/portalmq/__init__.py
import portalmq # precompiled from /home/blahblah/python_modules/portalmq/__init__.pyc
正如您所看到的,-v
标志只是向我提供有关导入哪些模块的信息,而不是有关哪个导入语句,哪个文件/行触发导入的信息。使用-vv
不会改变任何内容(显示已尝试模块的列表,但没有关于首先尝试导入的原因)
但我需要确切地知道:哪个import语句,哪个文件/行触发那些导入。我怎样才能获得这些信息?
答案 0 :(得分:5)
导入钩子!只需将此代码添加到主脚本入口点,即可在sys.meta_path.append
执行后跟踪每次导入。
import traceback
class TracingFinder:
def find_module(self, fullname, path=None):
print 'loading module', fullname
traceback.print_stack()
import sys
sys.meta_path.append(TracingFinder())
测试:
def foo():
import test
import this
foo()
输出:
loading module test
File "moo.py", line 15, in <module>
foo()
File "moo.py", line 12, in foo
import test
File "moo.py", line 6, in find_module
traceback.print_stack()
loading module this
File "moo.py", line 15, in <module>
foo()
File "moo.py", line 13, in foo
import this
File "moo.py", line 6, in find_module
traceback.print_stack()