我在我的python代碼中使用的第三方庫(用C編寫)發出警告。我希望能夠使用try
except
語法正確處理這些警告。有沒有辦法做到這一點?在Python中,如何捕獲警告,就好像它們是異常一樣?
49
A
回答
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
。
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
相關問題
- 1. 在Twig中讀取PersistentCollections,就好像它們是數組一樣
- 2. 驗證XSD在C#中,就好像它是一個XML:不給期待警告
- 3. 如何添加兩個字符串,就好像它們是數字一樣?
- 4. 如何使用二進制數字,就好像它們是字符串一樣
- 5. Python捕捉異常,但打印它們
- 6. CSS - 樣式ul元素,就好像它們是錶行元素
- 7. 捕獲所有異常,以便我可以報告它們
- 8. 如何在異常中捕獲異常?
- 9. 谷歌是否遵循jQuery「click」window.open,就好像它們是錨鏈接一樣?
- 10. 如何安裝gem,就好像它是在Gemfile中指定的一樣?
- 11. 如何捕獲Jasper報告圖像servlet中引發的異常
- 12. 如何在PHPUnit中捕獲PHP警告
- 13. 如何在F#中沒有警告的情況下捕獲任何異常(System.Exception)?
- 14. 需要任意文件,就好像它們在/ rails目錄中一樣
- 15. 如何捕獲CoreData警告?
- 16. 渲染對象,就好像它們是用鉛筆繪製的一樣?
- 17. 你可以添加兩個數字,就好像它們是正數一樣,即使它們可能是負數
- 18. 如何加入entit,就像它們是Doctrine 2中的表一樣?
- 19. 如何在Analysis Services中透明地顯示非添加性度量,就好像它們是添加劑一樣
- 20. 對齊複選框,就好像它們是一個線
- 21. Javascript添加數字,就好像它們是一個字符串
- 22. 製作2列的查詢,就好像它們是一個
- 23. 如何在python腳本中執行這一行代碼,就好像它是命令行一樣?
- 24. 「不要捕獲通用的異常!」但如何解開它們?
- 25. 動態html加載,就好像它在iframe中一樣
- 26. 我應該在哪裏捕獲Perl 6警告控件異常?
- 27. 捕獲MainLoop異常並在MessageDialogs中顯示它們
- 28. 如何隱藏GridViewColumn,就好像它在運行時在WPF中摺疊一樣?
- 29. python - for循環中的變量就好像它不存在一樣
- 30. 如何通過lamba表達式傳遞一個捕獲的變量,就像它未被捕獲一樣?
這些警告只是短信寫入stderr嗎? – Fenikso 2011-04-13 05:40:00
Fenikso:我不確定,看起來像是真實的警告 – 2011-04-13 05:52:22
你如何認識到「真正的警告」?我認爲在編譯過程中你會得到真正的警告。 – Fenikso 2011-04-13 06:06:37