问题描述
我在带有 Windows 终端的 Windows 10 上使用 Git Bash,对于这个 Python 项目,ANSI 转义序列不起作用。
from colorama import init,Fore
from sys import stdout
init(convert=True)
# code ...
我尝试打印测试文本
# The code above
stdout.write('{GREEN}Test{RESET}'.format(GREEN=Fore.GREEN,RESET=Fore.RESET)
输出如下:
←[32mTest←[0m
我确信我的终端支持 ANSI 序列,因为我已经用 Bash、TS (Deno) 和 JS (NodeJS) 测试过它。他们都工作了。我还在命令提示符上进行了测试,它适用于 Python。也许这是 Git Bash 本身执行 Python 的问题?
我也尝试过直接编写十六进制代码,但仍然没有运气。检查下面的代码write.py
Example image
解决方法
浪费一些时间测试后,显然只使用 print
有效
#!/usr/bin/env python3
from colorama import init,Fore
from sys import stdout
# Initialize
init()
# Using `Fore`
print(f'{Fore.GREEN}Test{Fore.RESET}')
# Using actuall hex values
print('\x1B[31mTest\x1B[0m')
# Using stdout.write
stdout.write(f'{Fore.GREEN}Test{Fore.RESET}\n')
stdout.write('\x1B[31mTest\x1B[0m\n')
Test
Test
←[32mTest←[39m
←[31mTest←[0m
编辑:
使用 input
也会失败
# This will fail
xyz = input(f'{Fore.RED}Red text{Fore.RESET}')
# Consider using this as an alternative
print(f'{Fore.RED}Red text{Fore.RESET}',end='')
xyz = input()