VSCode:终端中的ANSI颜色

2024-09-19 11:21:57 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

但我只看到:

^{pr2}$

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

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


Tags: 代码in文本终端for颜色rangeit
2条回答

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

import colorama
colorama.init()

# your code with ansi sequences here

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

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

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

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

相关问题 更多 >