我正在使用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.
关于python - Telnetlib、字节串和 "invalid escape sequence",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53223306/