简体   繁体   English

如何检查导入python模块的原因?

[英]How to check why a python module is being imported?

I have a big library of python modules. 我有一个庞大的python模块库。 Sometimes, when importing a module, I see that unexpected modules are being imported. 有时,在导入模块时,我看到正在导入意外模块。 For this, I have been using python -v , to see which modules are being imported. 为此,我一直在使用python -v来查看正在导入的模块。 From the manpage: 从联机帮助页:

-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.

Well, this is not true. 嗯,这不是真的。 For example: 例如:

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

As you can see, the -v flag just gives me information about which modules are imported, but not about which import statement, in which file/line is triggering the import. 正如您所看到的, -v标志只是向我提供有关导入哪些模块的信息,而不是关于哪个import语句在哪个文件/行中触发导入的信息。 Using -vv does not change anything (a list of tried modules is shown, but nothing about why the import is tried in the first place) 使用-vv不会改变任何东西(显示已尝试模块的列表,但没有关于为什么首先尝试导入)

But I need to know exactly that: which import statement, in which file/line is triggering those imports. 但我需要确切地知道:哪个import语句,哪个文件/行触发那些导入。 How can I get this information? 我怎样才能获得这些信息?

Import hooks! 导入钩子! Just add this code to your main script entry point to track every import after the sys.meta_path.append is executed. 只需将此代码添加到主脚本入口点, sys.meta_path.append在执行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())

Test: 测试:

def foo():
    import test
    import this

foo()

Output: 输出:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM