使用input()时,Python3 bcolors产生奇怪的新行故障

时间:2019-03-15 21:49:45

标签: python-3.x

所以我正在ubuntu上进行python3项目,我需要彩色文本,并且通过快速的Google搜索,我发现bcolors满足了我的需要。唯一的问题是,当我将其与input()一起使用时,它永远不会换行,而只是在自身之上编写。

这是bcolors:

class bcolors:
 purple = '\033[95m'
 blue = '\033[94m'
 green = '\033[92m'
 yellow = '\033[93m'
 red = '\033[91m'
 cyan = '\033[96m'
 white = '\033[97m'
 grey = '\033[90m'
 end = '\033[0m'
 bold = '\033[1m'
 underline = '\033[4m'

示例:

输入

while True:
   x = input('{}input {}'.format(bcolors.green, bcolors.end))
   print(x)

第一行空间不足时:

 oddut it is really odd it is really odd it is really odd it is really 

代替

input it is really odd it is really odd it is really odd it is really it is really odd

enter image description here 有人知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

简单来说,您应该在非打印转义序列周围加上\x01(SOH)和\x02(STX)。

演示:

enter image description here

该演示的代码段:

#!/usr/bin/env python3
import re
import readline

def color(x):
    return '\033[92m' + x + '\033[0m'

def escape(x):
    return re.sub(r'(\033\[[\d;]+m)',
                  r'\001\1\002', x)

input(color('colored: '))
input(escape(color('escaped: ')))