6

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

一个.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

4 回答 4

12

您需要使用以下命令查找调用堆栈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]
于 2013-04-30T17:44:19.443 回答
3

您可以使用traceback.extract_stack

import traceback
def where():
    return traceback.extract_stack()[-2][0]
于 2013-04-30T17:48:21.827 回答
1
import sys

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

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

于 2013-04-30T17:47:09.957 回答
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__)))

Usingrealpath()应该可以处理从符号链接运行脚本的情况。

于 2013-04-30T17:58:48.837 回答