[英]How to colour a specific character cell in python using ansi escape codes where the character cell location is determined by variables
I would like to be able to colour a character cell in python where the character cell to be coloured is determined by two variables (one for the line one for the column). 我希望能够在python中为一个字符单元着色,其中要着色的字符单元由两个变量确定(一个用于列的第一行)。
I've tried string parsing and string concatenation but I can't work out why they don't work. 我已经尝试过字符串解析和字符串连接,但我无法弄清楚它们为什么不起作用。
sys.std(u"\u033[%d;%dH\u001b[47m\033[0m" % (y, x))
code = 47
sys.stdout.write(u"\u001b[81;23f\u001b[" + str(code) + "m " + RESET )
sys.stdout.write(u"\u001b[" + str(x) + ";23f\u001b[" + str(code) + "m " )
The first one says: SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-4: truncated \\uXXXX escape 第一个说:SyntaxError :( unicode error)'unicodeescape'编解码器无法解码位置0-4中的字节:截断\\ uXXXX转义
The second line works, it colours the character cell at line 81 column 23 grey. 第二行有效,它将第81行第23列灰色的字符单元着色。 But the third line prints "\[47m" at line 81 column 23 instead of outputting a coloured pixel.
但是第三行在第81行第23行打印“\\ u001b [47m”而不是输出彩色像素。
I don't really understand why the string concatenation works for the second one and not the third. 我真的不明白为什么字符串连接适用于第二个而不是第三个。 Ideally, I'd like to be able to change the values 81 and 23 using variables ie x and y.
理想情况下,我希望能够使用x和y等变量更改值81和23。
I've been pondering this for quite a few hours now and would appreciate some insight. 我一直在思考这个问题已经有好几个小时了,并且会很感激一些见解。
On python 3, the line 3 of your code works without changing. 在python 3上,代码的第3行无需更改即可正常工作。 On python 2, you need to cast all string members to unicode :
在python 2上,您需要将所有字符串成员强制转换为unicode:
sys.stdout.write(u"\u001b[" + unicode(x) + u";23f\u001b[" + unicode(code) + u"m " )
The first line seem to have another problem with the escape sequence as \\u033 isn't a valid escape char. 第一行似乎与转义序列有另一个问题,因为\\ u033不是有效的转义字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.