Reputation: 309
I have a module my_module
that it is sourced (imported) by lots of files using:
from my_module import *
Being inside the module, can I know which file imported this module ?
I would like to know the filename:line_no which made this import.
so code I require is:
my_module.py
print "This module is currently imported from: file:line_no = %s:%s" % what_in_here??
Upvotes: 2
Views: 94
Reputation: 98746
Place this in your 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]
Upvotes: 5