Determine where the function was executed?

how do I define a function, wherewhich can indicate where it was executed, without the arguments passed to? 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
+5
source share
4 answers

You need to find the call stack 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]
+11
source

You can use traceback.extract_stack:

import traceback
def where():
    return traceback.extract_stack()[-2][0]
+3
source
import sys

if __name__ == '__main__':
    print sys.argv[0]

sys.argv [0] - / , ,

+1

...

print where() # I want where() to return '~/app/b.py' like __file__ in b.py

... , , - script, .

...

import sys
import os

if __name__ == '__main__':
    print os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__)))

realpath() , script .

0

All Articles