how should I define a function, where
,which can tell where it was executed, with no arguments passed in?
all files in ~/app/
a.py:
def where():
return 'the file name where the function was executed'
b.py:
from a import where
if __name__ == '__main__':
print where() # I want where() to return '~/app/b.py' like __file__ in b.py
c.py:
from a import where
if __name__ == '__main__':
print where() # I want where() to return '~/app/c.py' like __file__ in c.py
In Chrome, you can use: console. trace(); Just add that line in your function, I usually place it as the first line. If you view the console you'll see the name of your function, and below that line you'll see where it's being called from.
You need to look up the call stack by using inspect.stack()
:
from inspect import stack
def where():
caller_frame = stack()[1]
return caller_frame[0].f_globals.get('__file__', None)
or even:
def where():
caller_frame = stack()[1]
return caller_frame[1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With