2013-04-30 60 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()應該在那裏你從一個符號鏈接運行腳本的情況下應付。