VSCode:终端中的 ANSI 颜色

VSCode: ANSI Colors in Terminal

如何使用 python 在终端中以 ansi 颜色打印文本? 我有这段代码来测试什么代码对文本有什么影响:

for i in range(0, 55):
    print(f"3[{i}mAt {i} THIS happens! 3[0m")

但我只看到:

←[0mAt 0 THIS happens! ←[0m
←[1mAt 1 THIS happens! ←[0m
←[2mAt 2 THIS happens! ←[0m
←[3mAt 3 THIS happens! ←[0m
←[4mAt 4 THIS happens! ←[0m
...

It works as intended in the online editor repl.it.

我知道主题设置中有 terminal.ansi 颜色,但如何访问它们?

转义序列因终端而异,如果 stdout 不是 tty,事情就会变得很奇怪。

在不依赖这些序列的情况下将颜色打印到终端的最简单方法是使用 blessings package。以下将以红色打印 hello 并以绿色打印 world(例如):

from blessings import Terminal
term = Terminal()
print(term.red("hello"), term.green("world"))

我会使用 colorama 包来支持 Windows 上的 ANSI 序列。

import colorama
colorama.init()

# your code with ansi sequences here

编辑:此方法与平台无关(不会在支持它们的终端上修改 ANSI 序列)并允许您在字符串中使用原始 ANSI 序列,并为您提供颜色定义。