Python中偶爾遇到的細節疑問(二):UnicodeDecodeError,警告與忽略警告warnings


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

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

import base64

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 類的子類

  • 忽略警告方法
import warnings
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."""

 

參考:

https://blog.csdn.net/sinat_25449961/article/details/83150624

https://blog.konghy.cn/2017/12/16/python-warnings/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM