Search code examples
pythontelnetansi-escape

How to open .txt file that contains ansi color codes


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

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

then it is correctly colorized for the client.

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

\033[32;1mHello!\033[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:

\033[32;1mHello!\033[0m

How do i make it also colorized?


Solution

  • 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])