如何在Python终端中打印彩色文本?

时间:2014-03-04 09:15:10

标签: python printing colors

我知道Stackoverflow here

提出了这个问题

所以我从joeld的回答中尝试了以下代码。

以下是IDLE中的代码(我使用的是Python 2.7):

print '\033[95m'+'my text'+'\033[95m'

我得到的输出没有变色:

[95mmy text[95m

=============================================== ================================

然后我也尝试了包colorama。该软件包安装在cmd

python setup.py install

并尝试使用Aptana Studio 3中的代码:

from colorama import *

print (Fore.GREEN + 'Green text')
print (Fore.Red + 'Red text')

我得到了以下输出:

[32mGreen text
Traceback (most recent call last):
  File "C:\Users\My Documents\Aptana Studio 3 Workspace\Practice\test_colorama.py", line 12, in <module>
    print (Fore.Red + 'Red text')
AttributeError: 'AnsiCodes' object has no attribute 'Red'

=============================================== ================================

所以现在我真的很困惑。这些解决方案被投票数百次,这意味着它应该是有效的,但在我的情况下似乎没有。

我可以知道如何在终端或控制台中打印彩色文本吗?

非常感谢。

2 个答案:

答案 0 :(得分:3)

没有Red

>>> import colorama
>>> colorama.Fore.Red
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'AnsiCodes' object has no attribute 'Red'

但是,RED存在:

>>> colorama.Fore.RED
'\x1b[31m'

答案 1 :(得分:1)

IDLE不是一个合适的shell。通过普通终端中的Python会话执行此操作。

相关问题