How to know who is importing me in python?

前端 未结 3 921
挽巷
挽巷 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:01

    The namedtuple code in the collections module has an example of how (and when) to do this:

    #cmn.py
    import sys
    print 'I am being imported by', sys._getframe(1).f_globals.get('__name__')
    

    One limitation of this approach is that the outermost module is always named __main__. If that is the case, the name of the outermost module can be determined from sys.argv[0].

    A second limitation is that if the code using sys._getframe is in the module scope it is only executed on the first import of cmn.py. You'd need to call a function of some sort after imports if you want to monitor all imports of the module.

提交回复
热议问题