I created a function to display a stack trace using inspect.
hello_world.py
# -*- coding: utf-8 -*-
import inspect
def printmessage(message):
record = inspect.stack()[1]
frame = record[0]
info = inspect.getframeinfo(frame)
fn = str(info.filename).split('/')[-1]
print '[TAG]' + fn + '#' + info.function + '(L:'+str(info.lineno) + ') : ' + message
def printstack():
for num in range(len(inspect.stack())):
if num == 0:
continue
record = inspect.stack()[num]
frame = record[0]
info = inspect.getframeinfo(frame)
fn = str(info.filename).split('/')[-1]
print '[TAG][' + str(num) + ']' + fn + '#' + info.function + '(L:'+str(info.lineno) + ')'
if __name__ == '__main__':
printmessage('hogehoge')
print ('-----------')
printstack()
result
[TAG]hello_world.py#<module>(L:23) : hogehoge
-----------
[TAG][1]hello_world.py#<module>(L:25)
[TAG][2]visualstudio_py_util.py#exec_code(L:95)
[TAG][3]visualstudio_py_util.py#exec_file(L:119)
[TAG][4]visualstudio_py_debugger.py#debug(L:2624)
[TAG][5]visualstudio_py_launcher.py#<module>(L:91)
[reference] https://docs.python.jp/3/library/inspect.html
Recommended Posts