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.
對警告的處理取決于你如何運(yùn)行解釋器以及一些其他配置。 例如,如果你使用 -W all 選項去運(yùn)行Python,你會得到如下的輸出:
bash % python3 -W all example.pyexample.py:5: DeprecationWarning: logfile argument is deprecated warnings.warn(’logfile argument is deprecated’, DeprecationWarning)
通常來講,警告會輸出到標(biāo)準(zhǔn)錯誤上。如果你想講警告轉(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 %
討論
在你維護(hù)軟件,提示用戶某些信息,但是又不需要將其上升為異常級別,那么輸出警告信息就會很有用了。 例如,假設(shè)你準(zhǔn)備修改某個函數(shù)庫或框架的功能,你可以先為你要更改的部分輸出警告信息,同時向后兼容一段時間。 你還可以警告用戶一些對代碼有問題的使用方式。
作為另外一個內(nèi)置函數(shù)庫的警告使用例子,下面演示了一個沒有關(guān)閉文件就銷毀它時產(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’>>>>
默認(rèn)情況下,并不是所有警告消息都會出現(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如何輸出警告信息的詳細(xì)內(nèi)容,更多關(guān)于Python 輸出警告信息的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
