Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何打开包含ansi颜色代码的.txt文件_Python_Telnet_Ansi - Fatal编程技术网

Python 如何打开包含ansi颜色代码的.txt文件

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

在用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;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])