使用Python在Powershell中打印彩色文本

问题描述 投票:0回答:1

我使用 termcolor 打印彩色文本,最终在 Powershell 中打印出奇怪的代码,因此我使用 colorama.init() 但它没有改变任何东西。我从 Stackoverflow 复制并发送了一些其他代码,因为我一开始未能导入 colorama。

import sys
from termcolor import colored
if sys.platform == 'win32': 
    try: 
        import colorama 
    except ImportError: 
        pass 
    else: 
        colorama.init()
text = colored("HI THERE!", color="magenta", on_color="on_cyan", attrs=["blink"])
print(text)

此代码在 Powershell 中打印出一条彩色消息(但它不会闪烁)。但是我不知道为什么这个较短的代码不起作用。 (它打印“[5m[46m[35mHI 那里![0m”]

from termcolor import colored
import colorama
colorama.init()
text = colored("HI THERE!", color="magenta", on_color="on_cyan", attrs=["blink"])
print(text)

我导入 termcolor 和 colorama;并在这两个代码中使用 init、colored 方法,但我不知道为什么它只适用于第一个代码。你知道这背后的原因是什么吗?提前致谢。

python-3.x powershell termcolor
1个回答
0
投票

您面临的问题是由于 Powershell 无法正确解释输出造成的。

“[5m[46m[35mHI 那里![0m””这些数字编码您为输出提供的颜色,但 shell 无法识别它们。

Colorama 曾经有一些参数来修复函数 init() 中的问题,但在最新版本中,他们鼓励在使用 Powershell 时使用另一种方法来初始化:

from colorama import just_fix_windows_console

just_fix_windows_console()

这应该可以解决你的问题

© www.soinside.com 2019 - 2024. All rights reserved.