在python中使用getfile()方法獲取函數路徑,具體方法如下:
import os
import inspect
import external_def
def foo():
pass
print os.path.abspath(inspect.getfile(foo))
print os.path.abspath(inspect.getfile(external_def.bar))
$cat external_def.py
def bar():
pass
輸出結果為:
$python inspect-example.py
/home/chuckx/code/stackoverflow/inspect-example.py
/home/chuckx/code/stackoverflow/external_def.py