我應該如何定義一個函數,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
正如你所注意到的,你已經有了想要的信息作爲'__file__'。爲什麼你需要編寫一個函數來返回它? – kindall 2013-04-30 17:43:32
看看這裏:http://docs.python.org/2/library/inspect.html – StoryTeller 2013-04-30 17:43:32
@kindall我希望where()知道它在哪裏執行,並將它用作其函數體中的變量。 – walknotes 2017-09-17 04:07:39