Python 3 Regex TypeError: expected string or bytes-like object

Python 3 Regex TypeError: expected string or bytes-like object

我正在尝试使用 Paramiko 模块解析 SSH 会话的输出。 Paramiko channel.recv() returns 输出是字节。然后我使用 bytes.decode("utf-8") 将它转换为 UTF-8 字符串。无论我使用什么编码,正则表达式总是引发 TypeError: expected string or bytes-like object 异常。

import re

bytes = b"optical temp=10950"
bytes = bytes.decode("utf-8")

pattern = re.compile("(?<=temp=).*")
temp = re.search(bytes, pattern)

回溯:

Traceback (most recent call last):
  File "main.py", line 7, in <module>
    temp = re.search(bytes, pattern)
  File "/usr/lib/python3.8/re.py", line 201, in search
    return _compile(pattern, flags).search(string)
TypeError: expected string or bytes-like object

您的代码几乎可以正常工作。

re.search 先取模式,再取要搜索的字符串:

import re

bytes = b"optical temp=10950"
bytes = bytes.decode("utf-8")

pattern = re.compile("(?<=temp=).*")
temp = re.search(pattern, bytes)
#OR
temp = pattern.search(bytes)