2013-04-30 59 views
5

我应该如何定义一个函数,where,它可以告诉它在哪里执行,没有参数传入? 所有文件在〜/应用/确定函数的执行位置?

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

正如你所注意到的,你已经有了想要的信息作为'__file__'。为什么你需要编写一个函数来返回它? – kindall 2013-04-30 17:43:32

+0

看看这里:http://docs.python.org/2/library/inspect.html – StoryTeller 2013-04-30 17:43:32

+0

@kindall我希望where()知道它在哪里执行,并将它用作其函数体中的变量。 – walknotes 2017-09-17 04:07:39

回答

11

你需要仰视调用堆栈使用inspect.stack()

from inspect import stack 

def where(): 
    caller_frame = stack()[1] 
    return caller_frame[0].f_globals.get('__file__', None) 

甚至:

def where(): 
    caller_frame = stack()[1] 
    return caller_frame[1] 
1
import sys 

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

sys.argv中[0]始终是运行文件的名称/路径,甚至不带参数的

3

已过,您可以使用traceback.extract_stack

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

在此基础上...

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

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

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

import sys 
import os 

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

使用realpath()应该在那里你从一个符号链接运行脚本的情况下应付。