简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM