Python如何輸出警告信息
問題
你希望自己的程序能生成警告信息(比如廢棄特性或使用問題)。
解決方案
要輸出一個警告消息,可使用 warning.warn() 函數。例如:
import warningsdef func(x, y, logfile=None, debug=False): if logfile is not None: warnings.warn(’logfile argument deprecated’, DeprecationWarning) ...
warn() 的參數是一個警告消息和一個警告類,警告類有如下幾種: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)
通常來講,警告會輸出到標準錯誤上。如果你想講警告轉換為異常,可以使用 -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 %
討論
在你維護軟件,提示用戶某些信息,但是又不需要將其上升為異常級別,那么輸出警告信息就會很有用了。 例如,假設你準備修改某個函數庫或框架的功能,你可以先為你要更改的部分輸出警告信息,同時向后兼容一段時間。 你還可以警告用戶一些對代碼有問題的使用方式。
作為另外一個內置函數庫的警告使用例子,下面演示了一個沒有關閉文件就銷毀它時產生的警告消息:
>>> 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’>>>>
默認情況下,并不是所有警告消息都會出現。-W 選項能控制警告消息的輸出。 -W all 會輸出所有警告消息,-W ignore 忽略掉所有警告,-W error 將警告轉換成異常。 另外一種選擇,你還可以使用 warnings.simplefilter() 函數控制輸出。 always 參數會讓所有警告消息出現,`ignore 忽略調所有的警告,error 將警告轉換成異常。
對于簡單的生成警告消息的情況這些已經足夠了。 warnings 模塊對過濾和警告消息處理提供了大量的更高級的配置選項。 更多信息請參考 Python文檔
以上就是Python如何輸出警告信息的詳細內容,更多關于Python 輸出警告信息的資料請關注好吧啦網其它相關文章!
相關文章:
