Skip to main content
 首页 » 编程设计

python之Telnetlib、字节串和 "invalid escape sequence"

2024年09月03日24findumars

显然,我正在使用 telnetlib.expect() 与以字节串响应的设备交互。除非我在传递给 expect() 的正则表达式中使用字节字符串(预编译或文字),否则会生成异常:TypeError: cannot use a string pattern on a bytes-like object。然而,pycodestyle 提示这是 W605 invalid escape sequence '\d',进一步阅读让我认为这将成为 future 的 Python 语法错误。

总结:

telnetlib.expect([b'\d']) # OK, but W065 
telnetlib.expect(['\d'] # TypeError 
telnetlib.expect([r'\d'] # TypeError 

有办法解决这个问题,还是 pycodestyle 完全错误?

(顺便说一句,除了抑制所有警告之外,似乎无法抑制 pycodestyle 中的 W065。)

请您参考如下方法:

字节串文字使用 \ 作为转义字符,就像字符串文字一样。与它们非常相似,您必须使用原始字节串文字 rb'\d' 或使用双反斜杠 b'\\d'。

来自 https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals

In plain English: Both types of literals can be enclosed in matching single quotes (') or double quotes ("). They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as triple-quoted strings). The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.