3

我有一个很大的 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不会改变任何东西(显示了已尝试模块的列表,但没有说明为什么首先尝试导入)

但我需要确切地知道:哪个导入语句,哪个文件/行触发了这些导入。我怎样才能得到这些信息?

4

1 回答 1

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()
于 2012-10-10T06:47:09.037 回答