AlwaysQuestioning
AlwaysQuestioning

Reputation: 1484

Python3 breaking valid Python2 code: How can I send a series of bytes in a buffer in a socket in Python?

Basic question, but if I have socket s and I want to do:

s.sendto(("\u001b" + 47 * "1"), (mysite.com, 80))

How can I do this without the \u001b being converted to "ESC" in Python3 and making my program not run? This works in Python2.

Upvotes: 1

Views: 51

Answers (1)

Vasili Syrakis
Vasili Syrakis

Reputation: 9601

In Python 3 you need to encode the string explicitly

You can do this a couple ways, but this might be the easiest:

payload = bytes("\u001b" + 47 * "1", 'utf-8')
s.sendto(payload, (mysite.com, 80))

In this case, the arguments we are using are:

bytes(string, encoding[, errors]) -> bytes

If you wanted to use a list of integers instead, you could try the following:

# 27 == ord('\x1b')
# 49 == ord('1')
bytes([27] + [49] * 47)
# b'\x1b11111111111111111111111111111111111111111111111'

Upvotes: 1

Related Questions