确定函数的执行位置?

时间:2022-04-14 19:32:54

how should I define a function, where,which can tell where it was executed, with no arguments passed in? all files in ~/app/

我应该如何定义一个函数,哪里可以告诉它在哪里执行,没有传入参数? 〜/ 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

4 个解决方案

#1


11  

You need to look up the call stack by using inspect.stack():

您需要使用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]

#2


3  

You can use traceback.extract_stack:

您可以使用traceback.extract_stack:

import traceback
def where():
    return traceback.extract_stack()[-2][0]

#3


1  

import sys

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

sys.argv[0] is always the name/path of the file running, even with no arguments passed in

sys.argv [0]始终是运行文件的名称/路径,即使没有传入参数也是如此

#4


0  

Based on this...

基于此......

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

...it sounds more like what you want is the qualified path of the script you're executing.

...听起来更像你想要的是你正在执行的脚本的合格路径。

In which case, try...

在这种情况下,试试......

import sys
import os

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

Using realpath() should cope with the case where you're running the script from a symbolic link.

使用realpath()应该处理从符号链接运行脚本的情况。

#1


11  

You need to look up the call stack by using inspect.stack():

您需要使用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]

#2


3  

You can use traceback.extract_stack:

您可以使用traceback.extract_stack:

import traceback
def where():
    return traceback.extract_stack()[-2][0]

#3


1  

import sys

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

sys.argv[0] is always the name/path of the file running, even with no arguments passed in

sys.argv [0]始终是运行文件的名称/路径,即使没有传入参数也是如此

#4


0  

Based on this...

基于此......

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

...it sounds more like what you want is the qualified path of the script you're executing.

...听起来更像你想要的是你正在执行的脚本的合格路径。

In which case, try...

在这种情况下,试试......

import sys
import os

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

Using realpath() should cope with the case where you're running the script from a symbolic link.

使用realpath()应该处理从符号链接运行脚本的情况。