使用ANSI转义码(Windows)在Python 3.8中更改控制台打印颜色

3
我正在尝试使用ANSI转义码在Python shell中打印彩色代码。 我的代码看起来像这样:
print("\033[031m" + "Hello" + "\033[0m")

当我在 Visual Studio Code 中运行代码时,它可以完美地工作,但如果我直接在 Python 3.8 中打开它,我的输出是:[031m你好[0m


尝试使用这个库:https://pypi.org/project/colorama/ - undefined
2
你必须明白,使用转义码与你运行代码的终端类型密切相关。显然,VSCode的终端支持一些代码,而你所谓的“直接在Python中”运行则在另一个终端中。 - undefined
2个回答

4

在Windows系统中,在打印命令之前尝试清除屏幕:

import os
os.system("cls")
print("\033[031m" + "Hello" + "\033[0m")

它有效,但为什么呢? - undefined

2
尝试使用Colorama:
from colorama import Fore, Back, Style
print(Fore.RED + 'some red text')
print(Back.GREEN + 'and with a green background')
print(Style.DIM + 'and in dim text')
print(Style.RESET_ALL)
print('back to normal now')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接