Telnetlib、字节串和 "invalid escape sequence"
Telnetlib, bytestrings, and "invalid escape sequence"
我正在使用 telnetlib.expect()
来连接一个以字节串响应的设备,显然。除非我在传递给 expect()
的正则表达式中使用字节串(预编译或文字),否则会生成异常:TypeError: cannot use a string pattern on a bytes-like object
。然而,pycodestyle
抱怨这是 W605 invalid escape sequence '\d'
,进一步阅读让我认为这将在未来成为 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.
我正在使用 telnetlib.expect()
来连接一个以字节串响应的设备,显然。除非我在传递给 expect()
的正则表达式中使用字节串(预编译或文字),否则会生成异常:TypeError: cannot use a string pattern on a bytes-like object
。然而,pycodestyle
抱怨这是 W605 invalid escape sequence '\d'
,进一步阅读让我认为这将在未来成为 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.