簡體   English   中英

確定函數的執行位置?

[英]Determine where a function was executed?

我應該如何定義一個函數, where可以告訴它在哪里執行,沒有傳入參數? 〜/ 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

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

您可以使用traceback.extract_stack

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

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

sys.argv [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()應該處理從符號鏈接運行腳本的情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM