Skip to content

Commit c52e4b0

Browse files
authored
Fix echo-content-escaped.py again (#26645)
The fix in #26615 only works in Py3. This time we make it compatible with Py2 & Py3.
1 parent cfcd8eb commit c52e4b0

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

FileAPI/file/resources/echo-content-escaped.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,13 @@
55
# As a convenience, CRLF newlines are left as is.
66

77
def escape_byte(byte):
8-
# Iterating over a 'bytes' type gives ints, so convert to bytes.
9-
byte = bytes([byte])
10-
if b"\0" <= byte <= b"\x1F" or byte >= b"\x7F":
11-
return b"\\x%02x" % ord(byte)
12-
if byte == b"\\":
8+
# Iterating over a binary string gives different types in Py2 & Py3.
9+
# Py3: bytes -> int
10+
# Py2: str -> str (of length 1), so we convert it to int
11+
code = byte if type(byte) is int else ord(byte)
12+
if 0 <= code <= 0x1F or code >= 0x7F:
13+
return b"\\x%02x" % code
14+
if code == ord(b"\\"):
1315
return b"\\\\"
1416
return byte
1517

0 commit comments

Comments
 (0)