日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

python运行不了、显示警告_Python中偶尔遇到的细节疑问(二):UnicodeDecodeError,警告与忽略警告warnings...

發布時間:2025/4/16 50 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python运行不了、显示警告_Python中偶尔遇到的细节疑问(二):UnicodeDecodeError,警告与忽略警告warnings... 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1. 使用base64解碼時,出現:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xed in position 21: invalid continuation byte

這里不是讀文件的時候,需要加入 encoding='utf-8' 等編碼格式的問題,而是:

importbase64

bb= r'44CQ5oqW6Z+z54Gr5bGx54mI44CR7aC9'ss= base64.b64decode(bb).decode('utf-8') #報錯:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xed in position 21: invalid continuation byte

原因是:其中存在子字符串無法被轉換,也就是部分二進制數據不能被decode。

解決方法:設置 'ignore' 即可。

ss = base64.b64decode(bb).decode('utf-8','ignore')

2. warnings類(警告與忽略警告)

內建警告類型主要有:

警告類類型描述

Warning

所有警告類別類的基類,它是 異常Exception 的子類

UserWarning

warn() 的默認類別

DeprecationWarning

用于已棄用或不推薦功能的警告(默認忽略)

SyntaxWarning

可疑語法特征的警告

RuntimeWarning

可疑運行時功能的警告

FutureWarning

對于未來特性更改的警告

PendingDeprecationWarning

將來會被棄用或不推薦的功能警告類別(默認忽略)

ImportWarning

導入模塊過程中觸發的警告(默認忽略)

UnicodeWarning

與 Unicode 相關的警告

BytesWarning

與 bytes 和 bytearray 相關的警告 (Python3)

ResourceWarning

與資源使用相關的警告(Python3)

可以通過繼承內建警告類型來實現自定義的警告類型,警告類型category必須始終是 Warning類的子類。

忽略警告方法:

importwarnings

warnings.filterwarnings("ignore")

函數 filterwarnings():用于過濾警告

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"

將匹配警告轉換為異常

"ignore"

不打印所匹配到的警告

"always"

一直輸出匹配的警告

"default"

對于同樣的警告只輸出第一次出現的警告

"module"

在一個模塊中只輸出首次出現的警告

"once"

輸出第一次出現的警告,不考慮它們的位置

message:用于匹配警告消息的正則表達式,不區分大小寫;默認值為空。

category:警告類型(但是必須是 Warning 的子類);默認值就是warning基類。

module:用于匹配模塊名稱的正則表達式,區分大小寫;默認值為空。

lineno:整數,表示警告發生的行號,為 0 則匹配所有行號;默認值是0。

append: 如果為真,則將條件放在過濾規則的末尾;默認False,即放在前面。

函數 warn():用于產生警告、忽略或者引發異常

def warn(message, category=None, stacklevel=1, source=None):"""Issue a warning, or maybe ignore it or raise an exception."""

參考:

總結

以上是生活随笔為你收集整理的python运行不了、显示警告_Python中偶尔遇到的细节疑问(二):UnicodeDecodeError,警告与忽略警告warnings...的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。