LoginSignup
2
5

More than 5 years have passed since last update.

[Python] inspectを使ってスタックトレースを表示する

Posted at

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()
結果
[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)

[参考]
https://docs.python.jp/3/library/inspect.html

2
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5