Find traceback of print caller

时间:2017-07-17 15:26:01

标签: python python-3.x

I am working on a python program which interacts with many external libraries and has some fairly complex logic. In this program I've found that it'll sometimes print NoneType: None to the console (with no context) whatsoever. I have no idea where this is being printed or why and this is causing errors in other places of the program.

So is it possible to find the source of a print/warn call?

1 个答案:

答案 0 :(得分:0)

您始终可以覆盖内置print()功能,然后观察正在发生的事情,例如:

import builtins
import inspect

builtin_print = builtins.print  # store a reference to the built-in print() function
def tracing_print(*args, **kwargs):
    c = inspect.getouterframes(inspect.currentframe())[1]  # get the calling frame
    # print the caller info (you can add a condition like `if args and args[0] is None`):
    builtin_print("{}, line {}, caller `{}`, source: {}".format(c[1], c[2], c[3], c[4]))
    builtin_print(*args, **kwargs)  # call the built-in method and forward the params
builtins.print = tracing_print  # override the built-in print

在每次拨打print()之前,这会给你很多信息。例如:

def foo():
    print("Bar!")
foo()

会产生类似的东西:

/tmp/playground/test.py, line 13, caller `foo`, source: ['    print("Bar!")\n']
Bar!

毋庸置疑,不要在生产代码中使用它,它适用于取证。

相关问题