Know filename: line_no where the import was made to my_module

I have a my_module module that it receives (is imported) by a variety of files using:

from my_module import *

Being inside a module, can I find out which file this module imported?
I would like to know the file name: line_no that made this import.

so i need code:

my_module.py

 print "This module is currently imported from: file:line_no = %s:%s" % what_in_here?? 
+2
source share
1 answer

Put this in the top-level module code:

 import traceback last_frame = traceback.extract_stack()[-2] print 'Module imported from file:line_no = %s:%i' % last_frame[:2] 

You can also use inspect instead of traceback :

 import inspect last_frame = inspect.stack()[1] print 'Module imported from file:line_no = %s:%i' % last_frame[1:3] 
+5
source

All Articles