2017-07-17 7 views
1

私は多くの外部ライブラリとやりとりし、かなり複雑なロジックを持っているpythonプログラムに取り組んでいます。このプログラムでは、時々コンソール(コンテキストなし)にNoneType: Noneを印刷することが判明しました。これがどこに印刷されているのか、なぜこれがプログラムの他の場所でエラーを引き起こしているのか分かりません。print callerのトレースバックを見つける

print/warnコールのソースを見つけることは可能ですか?

+1

おそらくこれは役に立ちます:https://stackoverflow.com/questions/10742501/is-there-a-trick-to-break-on-the-print-builtin-with-pdb – arshajii

+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!

は言うまでもないが、それは科学捜査のためのものです。