Python如何輸出警告信息
問題
你希望自己的程序能生成警告信息(比如廢棄特性或使用問題)。
解決方案
要輸出一個(gè)警告消息,可使用 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ù)是一個(gè)警告消息和一個(gè)警告類,警告類有如下幾種:UserWarning, DeprecationWarning, SyntaxWarning, RuntimeWarning, ResourceWarning, 或 FutureWarning.
對(duì)警告的處理取決于你如何運(yùn)行解釋器以及一些其他配置。 例如,如果你使用 -W all 選項(xiàng)去運(yùn)行Python,你會(huì)得到如下的輸出:
bash % python3 -W all example.pyexample.py:5: DeprecationWarning: logfile argument is deprecated warnings.warn(’logfile argument is deprecated’, DeprecationWarning)
通常來講,警告會(huì)輸出到標(biāo)準(zhǔn)錯(cuò)誤上。如果你想講警告轉(zhuǎn)換為異常,可以使用 -W error 選項(xiàng):
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ù)軟件,提示用戶某些信息,但是又不需要將其上升為異常級(jí)別,那么輸出警告信息就會(huì)很有用了。 例如,假設(shè)你準(zhǔn)備修改某個(gè)函數(shù)庫或框架的功能,你可以先為你要更改的部分輸出警告信息,同時(shí)向后兼容一段時(shí)間。 你還可以警告用戶一些對(duì)代碼有問題的使用方式。
作為另外一個(gè)內(nèi)置函數(shù)庫的警告使用例子,下面演示了一個(gè)沒有關(guān)閉文件就銷毀它時(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’>>>>
默認(rèn)情況下,并不是所有警告消息都會(huì)出現(xiàn)。-W 選項(xiàng)能控制警告消息的輸出。 -W all 會(huì)輸出所有警告消息,-W ignore 忽略掉所有警告,-W error 將警告轉(zhuǎn)換成異常。 另外一種選擇,你還可以使用 warnings.simplefilter() 函數(shù)控制輸出。 always 參數(shù)會(huì)讓所有警告消息出現(xiàn),`ignore 忽略調(diào)所有的警告,error 將警告轉(zhuǎn)換成異常。
對(duì)于簡(jiǎn)單的生成警告消息的情況這些已經(jīng)足夠了。 warnings 模塊對(duì)過濾和警告消息處理提供了大量的更高級(jí)的配置選項(xiàng)。 更多信息請(qǐng)參考 Python文檔
以上就是Python如何輸出警告信息的詳細(xì)內(nèi)容,更多關(guān)于Python 輸出警告信息的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 在Android中使用WebSocket實(shí)現(xiàn)消息通信的方法詳解2. python matplotlib:plt.scatter() 大小和顏色參數(shù)詳解3. Yii2.0引入CSS,JS文件方法4. JSP數(shù)據(jù)交互實(shí)現(xiàn)過程解析5. Python importlib動(dòng)態(tài)導(dǎo)入模塊實(shí)現(xiàn)代碼6. vue使用webSocket更新實(shí)時(shí)天氣的方法7. 淺談python出錯(cuò)時(shí)traceback的解讀8. android studio 打包自動(dòng)生成版本號(hào)與日期,apk輸入路徑詳解9. Nginx+php配置文件及原理解析10. JavaMail 1.4 發(fā)布
