如何从框架中获取文件路径

How to get the filepath from a frame

要从帧中获取文件名,我可以这样做:

exc_type, exc_value, exc_traceback = sys.exc_info()
current_frame = exc_traceback.tb_frame
filename = current_frame.f_code.co_filename
# example.py
# how to get '/Users/david/Desktop/Log/example.py' ?

但是,我没有找到获取文件路径的方法。如何从堆栈中获得完整的 filepath? (实际上,我目前看到的唯一方法是使用来自 traceback.format_exc() 的正则表达式,但这看起来很粗糙。)

os.path.abspath 应该可以为您解决这个问题:

filepath = os.path.abspath(current_frame.f_code.co_filename)