在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