2017-07-17 42 views
1

我正在研究一個與許多外部庫進行交互並具有一些相當複雜的邏輯的python程序。在這個程序中,我發現它有時會打印NoneType: None到控制檯(沒有任何上下文)。我不知道在哪裏打印這些信息,或者爲什麼這會導致程序的其他地方發生錯誤。查找打印調用者的追蹤

那麼是否有可能找到打印/警告呼叫的來源?

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

不用說,不要在生產代碼中使用此,它意味着取證。