2011-04-13 47 views
49

我在我的python代碼中使用的第三方庫(用C編寫)發出警告。我希望能夠使用tryexcept語法正確處理這些警告。有沒有辦法做到這一點?在Python中,如何捕獲警告,就好像它們是異常一樣?

+2

這些警告只是短信寫入stderr嗎? – Fenikso 2011-04-13 05:40:00

+1

Fenikso:我不確定,看起來像是真實的警告 – 2011-04-13 05:52:22

+1

你如何認識到「真正的警告」?我認爲在編譯過程中你會得到真正的警告。 – Fenikso 2011-04-13 06:06:37

回答

25

要從蟒蛇手冊(27.6.4. Testing Warnings)引述:

import warnings 

def fxn(): 
    warnings.warn("deprecated", DeprecationWarning) 

with warnings.catch_warnings(record=True) as w: 
    # Cause all warnings to always be triggered. 
    warnings.simplefilter("always") 
    # Trigger a warning. 
    fxn() 
    # Verify some things 
    assert len(w) == 1 
    assert issubclass(w[-1].category, DeprecationWarning) 
    assert "deprecated" in str(w[-1].message) 

(編輯:固定的例子,被關段)

+3

[這裏](http://stackoverflow.com/a/15934081/461597)是一個答案,它告訴你如何使用'try'' except語法。 – Unapiedra 2014-10-10 13:12:02

11

這裏有一個變化,使得它更清楚如何在只自定義工作警告。

import warnings 
with warnings.catch_warnings(record=True) as w: 
    # Cause all warnings to always be triggered. 
    warnings.simplefilter("always") 

    # Call some code that triggers a custom warning. 
    functionThatRaisesWarning() 

    # ignore any non-custom warnings that may be in the list 
    w = filter(lambda i: issubclass(i.category, UserWarning), w) 

    if len(w): 
     # do something with the first warning 
     email_admins(w[0].message) 
40

要處理warnnings爲錯誤簡單地使用這樣的:

import warnings 
warnings.filterwarnings("error") 

此之後,你將能夠趕上相同的錯誤,例如警告這將工作:

try: 
    some_heavy_calculations() 
except RuntimeWarning: 
    import ipdb; ipdb.set_trace() 

P.S.添加了此答案,因爲評論中的最佳答案包含拼寫錯誤:filterwarnigns而不是filterwarnings

+2

如果你只是想看到一個堆棧跟蹤,前兩行是你所需要的。 – z0r 2017-02-23 00:59:30

+1

這是完美的。我只是希望腳本在發出警告後立即停止執行,以便打印相關調試信息並解決問題。 – Praveen 2017-04-26 15:53:34

6

如果你只是想讓你的腳本失敗的警告,你可以使用:

python -W error foobar.py 
0

在某些情況下,你需要使用ctypes的把警告變爲錯誤。例如:

str(b'test') # no error 
import warnings 
warnings.simplefilter('error', BytesWarning) 
str(b'test') # still no error 
import ctypes 
ctypes.c_int.in_dll(ctypes.pythonapi, 'Py_BytesWarningFlag').value = 2 
str(b'test') # this raises an error 
相關問題