Python如何輸出警告信息
問題
你希望自己的程序能生成警告信息(比如廢棄特性或使用問題)。
解決方案
要輸出一個警告消息,可使用 warning.warn() 函數(shù)。例如:
import warningsdef func(x, y, logfile=None, debug=False): if logfile is not None: warnings.warn(’logfile argument deprecated’, DeprecationWarning) ...
warn() 的參數(shù)是一個警告消息和一個警告類,警告類有如下幾種:UserWarning, DeprecationWarning, SyntaxWarning, RuntimeWarning, ResourceWarning, 或 FutureWarning.
對警告的處理取決于你如何運行解釋器以及一些其他配置。 例如,如果你使用 -W all 選項去運行Python,你會得到如下的輸出:
bash % python3 -W all example.pyexample.py:5: DeprecationWarning: logfile argument is deprecated warnings.warn(’logfile argument is deprecated’, DeprecationWarning)
通常來講,警告會輸出到標準錯誤上。如果你想講警告轉(zhuǎn)換為異常,可以使用 -W error 選項:
bash % python3 -W error example.pyTraceback (most recent call last): File 'example.py', line 10, in <module> func(2, 3, logfile=’log.txt’) File 'example.py', line 5, in func warnings.warn(’logfile argument is deprecated’, DeprecationWarning)DeprecationWarning: logfile argument is deprecatedbash %
討論
在你維護軟件,提示用戶某些信息,但是又不需要將其上升為異常級別,那么輸出警告信息就會很有用了。 例如,假設你準備修改某個函數(shù)庫或框架的功能,你可以先為你要更改的部分輸出警告信息,同時向后兼容一段時間。 你還可以警告用戶一些對代碼有問題的使用方式。
作為另外一個內(nèi)置函數(shù)庫的警告使用例子,下面演示了一個沒有關閉文件就銷毀它時產(chǎn)生的警告消息:
>>> import warnings>>> warnings.simplefilter(’always’)>>> f = open(’/etc/passwd’)>>> del f__main__:1: ResourceWarning: unclosed file <_io.TextIOWrapper name=’/etc/passwd’ mode=’r’ encoding=’UTF-8’>>>>
默認情況下,并不是所有警告消息都會出現(xiàn)。-W 選項能控制警告消息的輸出。 -W all 會輸出所有警告消息,-W ignore 忽略掉所有警告,-W error 將警告轉(zhuǎn)換成異常。 另外一種選擇,你還可以使用 warnings.simplefilter() 函數(shù)控制輸出。 always 參數(shù)會讓所有警告消息出現(xiàn),`ignore 忽略調(diào)所有的警告,error 將警告轉(zhuǎn)換成異常。
對于簡單的生成警告消息的情況這些已經(jīng)足夠了。 warnings 模塊對過濾和警告消息處理提供了大量的更高級的配置選項。 更多信息請參考 Python文檔
以上就是Python如何輸出警告信息的詳細內(nèi)容,更多關于Python 輸出警告信息的資料請關注好吧啦網(wǎng)其它相關文章!
相關文章:
1. ajax請求添加自定義header參數(shù)代碼2. Gitlab CI-CD自動化部署SpringBoot項目的方法步驟3. 基于javascript處理二進制圖片流過程詳解4. 淺談SpringMVC jsp前臺獲取參數(shù)的方式 EL表達式5. 教你如何寫出可維護的JS代碼6. ASP中解決“對象關閉時,不允許操作。”的詭異問題……7. 使用Python和百度語音識別生成視頻字幕的實現(xiàn)8. ASP刪除img標簽的style屬性只保留src的正則函數(shù)9. Django-migrate報錯問題解決方案10. Java Lock接口實現(xiàn)原理及實例解析
