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/

原文地址:https://www.cnblogs.com/qi-yuan-008/p/13033563.html