如何确定文件、函数和行号?
在C++中,我可以这样打印调试信息:
printf(
"FILE: %s, FUNC: %s, LINE: %d, LOG: %s\n",
__FILE__,
__FUNCTION__,
__LINE__,
logmessage
);
那我在Python中怎么做类似的事情呢?
10 个回答
12
基于geowar的回答:
class __LINE__(object):
import sys
def __repr__(self):
try:
raise Exception
except:
return str(sys.exc_info()[2].tb_frame.f_back.f_lineno)
__LINE__ = __LINE__()
如果你通常想在比如说print
(或者其他需要隐式调用str()
或repr()
的地方)中使用__LINE__
,那么上面的内容可以让你省略()
。
(显而易见的扩展是添加一个__call__
,留给读者自己去练习。)
13
例如
import inspect
frame = inspect.currentframe()
# __FILE__
fileName = frame.f_code.co_filename
# __LINE__
fileNo = frame.f_lineno
95
有一个叫做 inspect
的模块,它可以提供这些信息。
下面是一个使用的例子:
import inspect
def PrintFrame():
callerframerecord = inspect.stack()[1] # 0 represents this line
# 1 represents line at caller
frame = callerframerecord[0]
info = inspect.getframeinfo(frame)
print(info.filename) # __FILE__ -> Test.py
print(info.function) # __FUNCTION__ -> Main
print(info.lineno) # __LINE__ -> 13
def Main():
PrintFrame() # for this line
Main()
不过,请记住,还有一种更简单的方法可以获取当前正在执行的文件名:
print(__file__)