python运行不了、显示警告_Python中偶尔遇到的细节疑问(二):UnicodeDecodeError,警告与忽略警告warnings...
1. 使用base64解碼時(shí),出現(xiàn):UnicodeDecodeError: 'utf-8' codec can't decode byte 0xed in position 21: invalid continuation byte
這里不是讀文件的時(shí)候,需要加入 encoding='utf-8' 等編碼格式的問(wèn)題,而是:
importbase64
bb= r'44CQ5oqW6Z+z54Gr5bGx54mI44CR7aC9'ss= base64.b64decode(bb).decode('utf-8') #報(bào)錯(cuò):UnicodeDecodeError: 'utf-8' codec can't decode byte 0xed in position 21: invalid continuation byte
原因是:其中存在子字符串無(wú)法被轉(zhuǎn)換,也就是部分二進(jìn)制數(shù)據(jù)不能被decode。
解決方法:設(shè)置 'ignore' 即可。
ss = base64.b64decode(bb).decode('utf-8','ignore')
2. warnings類(警告與忽略警告)
內(nèi)建警告類型主要有:
警告類類型描述
Warning
所有警告類別類的基類,它是 異常Exception 的子類
UserWarning
warn() 的默認(rèn)類別
DeprecationWarning
用于已棄用或不推薦功能的警告(默認(rèn)忽略)
SyntaxWarning
可疑語(yǔ)法特征的警告
RuntimeWarning
可疑運(yùn)行時(shí)功能的警告
FutureWarning
對(duì)于未來(lái)特性更改的警告
PendingDeprecationWarning
將來(lái)會(huì)被棄用或不推薦的功能警告類別(默認(rèn)忽略)
ImportWarning
導(dǎo)入模塊過(guò)程中觸發(fā)的警告(默認(rèn)忽略)
UnicodeWarning
與 Unicode 相關(guān)的警告
BytesWarning
與 bytes 和 bytearray 相關(guān)的警告 (Python3)
ResourceWarning
與資源使用相關(guān)的警告(Python3)
可以通過(guò)繼承內(nèi)建警告類型來(lái)實(shí)現(xiàn)自定義的警告類型,警告類型category必須始終是 Warning類的子類。
忽略警告方法:
importwarnings
warnings.filterwarnings("ignore")
函數(shù) filterwarnings():用于過(guò)濾警告
def filterwarnings(action, message="", category=Warning, module="", lineno=0,
append=False):"""Insert an entry into the list of warnings filters (at the front).
'action' -- one of "error", "ignore", "always", "default", "module",
or "once"
'message' -- a regex that the warning message must match
'category' -- a class that the warning must be a subclass of
'module' -- a regex that the module name must match
'lineno' -- an integer line number, 0 matches all warnings
'append' -- if true, append to the list of filters"""
action:
"error"
將匹配警告轉(zhuǎn)換為異常
"ignore"
不打印所匹配到的警告
"always"
一直輸出匹配的警告
"default"
對(duì)于同樣的警告只輸出第一次出現(xiàn)的警告
"module"
在一個(gè)模塊中只輸出首次出現(xiàn)的警告
"once"
輸出第一次出現(xiàn)的警告,不考慮它們的位置
message:用于匹配警告消息的正則表達(dá)式,不區(qū)分大小寫;默認(rèn)值為空。
category:警告類型(但是必須是 Warning 的子類);默認(rèn)值就是warning基類。
module:用于匹配模塊名稱的正則表達(dá)式,區(qū)分大小寫;默認(rèn)值為空。
lineno:整數(shù),表示警告發(fā)生的行號(hào),為 0 則匹配所有行號(hào);默認(rèn)值是0。
append: 如果為真,則將條件放在過(guò)濾規(guī)則的末尾;默認(rèn)False,即放在前面。
函數(shù) warn():用于產(chǎn)生警告、忽略或者引發(fā)異常
def warn(message, category=None, stacklevel=1, source=None):"""Issue a warning, or maybe ignore it or raise an exception."""
參考:
總結(jié)
以上是生活随笔為你收集整理的python运行不了、显示警告_Python中偶尔遇到的细节疑问(二):UnicodeDecodeError,警告与忽略警告warnings...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: shell 中diff返回值_LINUX
- 下一篇: for循环里radio多选_Max里的f