How to know who is importing me in python?

前端 未结 3 931
挽巷
挽巷 2021-01-02 03:30

How can I find out what file is importing a particular file in python?

Consider the following example:

#a.py
import cmn
....

#b.py
import cmn
...

#         


        
3条回答
  •  一个人的身影
    2021-01-02 04:16

    Well, this is a kind of bizarre thing to do. You haven't explained why you want to know what is importing your module, so I can't actually help you solve your problem. You also haven't explained how or when you want to know the importing module.

    def who_imports(studied_module):
        for loaded_module in sys.modules.values():
            for module_attribute in dir(loaded_module):
                if getattr(loaded_module, module_attribute) is studied_module:
                    yield loaded_module
    

    This will give you an iterator over all the modules which use your module as a top-level object. It won't find modules that do from cmn import *, and the list will change over time.

    >>> import os
    >>> for m in who_imports(os):
    ...     print m.__name__
    ... 
    site
    __main__
    posixpath
    genericpath
    posixpath
    linecache
    

提交回复
热议问题