Python 如何打开包含ansi颜色代码的.txt文件
在用python编写的telnet服务器中,如果我向客户端套接字发送如下消息:Python 如何打开包含ansi颜色代码的.txt文件,python,telnet,ansi,Python,Telnet,Ansi,在用python编写的telnet服务器中,如果我向客户端套接字发送如下消息: socket.send("\033[32;1mHello!\033[0m") f = io.open("files/hello.txt",'r') message = f.read() f.close() socket.send(message) \033[32;1mHello!\033[0m 然后为客户端正确着色 但当我使用文本文件时,例如,hello.txt,其中包含以下内容: \033[32;1mHell
socket.send("\033[32;1mHello!\033[0m")
f = io.open("files/hello.txt",'r')
message = f.read()
f.close()
socket.send(message)
\033[32;1mHello!\033[0m
然后为客户端正确着色
但当我使用文本文件时,例如,hello.txt,其中包含以下内容:
\033[32;1mHello!\033[0m
然后像这样发送:
socket.send("\033[32;1mHello!\033[0m")
f = io.open("files/hello.txt",'r')
message = f.read()
f.close()
socket.send(message)
\033[32;1mHello!\033[0m
然后文本不着色,显示方式如下:
socket.send("\033[32;1mHello!\033[0m")
f = io.open("files/hello.txt",'r')
message = f.read()
f.close()
socket.send(message)
\033[32;1mHello!\033[0m
如何使其也着色?从文件读取时,反斜杠将被转义,因此请尝试:
socket.send(message.decode('string_escape'))
请查看文档以进一步参考:。但这在python3中可能不起作用
更新:对于python3,您必须:
import codecs
socket.send(codecs.getdecoder('unicode_escape')(message)[0])