How to open .txt file that contains ansi color codes

Question:

In my telnet server written in python, if i send a message to client socket like this:

socket.send("33[32;1mHello!33[0m")

then it is correctly colorized for the client.

But when i use a text file, for example, hello.txt with such content:

33[32;1mHello!33[0m

and send it like this:

f = io.open("files/hello.txt",'r')
message = f.read()
f.close()
socket.send(message)

then text is not colorized and appears like this:

33[32;1mHello!33[0m

How do i make it also colorized?

Asked By: lxknvlk

||

Answers:

The backslashes will be escaped when read from the file, so try:

socket.send(message.decode('string_escape'))

Have a look at the docs for further reference: https://docs.python.org/2/library/codecs.html#python-specific-encodings. This may not work in python3 though.

Update: Turns out for python3 you’d have to:

import codecs
socket.send(codecs.getdecoder('unicode_escape')(message)[0])
Answered By: deif
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.