我已经为Python安装了colorama。我按照以下方式导入了该模块:
import colorama
from colorama import init
init()
from colorama import Fore, Back, Style
print Fore.RED + "My Text is Red"
它返回 ANSI 字符....
esc[31mMy Text is Red
这不是我预期的结果。我做错了什么吗?
谢谢。
我已经为Python安装了colorama。我按照以下方式导入了该模块:
import colorama
from colorama import init
init()
from colorama import Fore, Back, Style
print Fore.RED + "My Text is Red"
它返回 ANSI 字符....
esc[31mMy Text is Red
这不是我预期的结果。我做错了什么吗?
谢谢。
我在Windows 7 x64上也遇到了同样的问题,最终通过在init调用中添加参数convert=True
,无需安装任何新软件就解决了颜色显示问题。
from colorama import init, Fore, Back, Style
init(convert=True)
print(Fore.RED + 'some red text')
init(convert=True)
参数或其他任何东西,它也不起作用。对我来说,它只能在代码的前100行中工作。我不知道为什么。也许如果有人能帮忙就好了 :) 编辑:虽然我晚了,但我会很感激,因为这是我几个月以来一直面临的问题! - The Myth我从未成功地在Windows cmd.exe中使用颜色而不需要使用colorama等工具。 在打了Ansicon补丁后,ANSI颜色代码将能够正常工作(colorama 对我也不起作用)。
要使用Ansicon为cmd.exe打补丁,请执行以下操作:
ansicon.exe -i
来源:https://dev59.com/OG445IYBdhLWcg3wq8Lp#4749307
此外,如果您拥有NVidia显卡,则可能需要将环境变量“ANSICON_EXC”设置为“nvd3d9wrap.dll”。
我意识到这是一个非常老旧的问题,但是现有的答案都没有帮助到我,所以我要发布我的解决方案,以防其他人也遇到同样的问题。在我的情况下,问题在于我导入了来自sys
的stdout
,然后初始化了colorama
,这是行不通的:
>>> from colorama import Fore, Style, init
>>> from sys import stdout
>>> init()
>>> stdout.write(Fore.RED + Style.BRIGHT + "Test" + Style.RESET_ALL + "\n")
[31m[1mTest[0m
>>> from colorama import Fore, Style, init
>>> init()
>>> from sys import stdout
>>> stdout.write(Fore.RED + Style.BRIGHT + "Test" + Style.RESET_ALL + "\n")
Test <--- This is now bright red.
在Windows 10 64位系统上,Anaconda Prompt(实质上是cmd.exe)对我有用。Colorama can be used happily in conjunction with existing ANSI libraries such as Termcolor
from colorama import init from termcolor import colored # use Colorama to make Termcolor work on Windows too init() # then use Termcolor for all colored text output print(colored('Hello, World!', 'green', 'on_red'))
打印前清除命令提示符
import os
from colorama import init,Fore
init()
os.system("cls" or "clear")
print Fore.RED + "My Text is Red"
我知道这是一个旧帖子,但我会回答任何新来的人。对我而言,基本上有效的方法是在打印彩色文本之前放置控制台清除命令。
例如,不要这样做:
#random code above
def print_string():
print(f'{Fore.YELLOW} Hello World {Fore.RESET}')
#random code above
def print_string():
os.system('cls' if os.name == 'nt' else 'clear') # multi-platform clear statement
print(f'{Fore.YELLOW} Hello World {Fore.RESET}')
我不知道它是如何工作的,但在特定区域清除控制台似乎可以解决你的问题。我之前也遇到过这个问题,一个朋友建议我这样做,结果有效了。希望对你有所帮助。
(这也可以修复ANSI转义码的问题,以及colorama的问题。)
添加
colorama.init()
或者
from colorama import init
init()
回到你的代码,它就会正常工作。
这很正常,因为在Windows上你没有ANSI
。
尝试使用tendo.colorer之类的东西,这将使所有平台都能够进行着色。
注意:tendo.colorer会向日志添加颜色,但我相信你会想出如何将其用于其他事情。如果我没记错的话,在你的代码之前导入它就可以解决问题了。
只需将此粘贴到导入的末尾即可,Ez
init(convert=True)
os.system("mode 360")
os.system("cls")
你只能使用一个import导入,例如:
from colorama import init, Fore, Back, Style
init()
现在你可以尝试一下:
print(Fore.RED + 'some red text')
print(Back.GREEN + 'and with a green background')
print(Style.DIM + 'and in dim text')
print(Fore.RESET + Back.RESET + Style.RESET_ALL)
cmd
和 Cygwin 上都能运行。(Windows 10,Python35) - user3917838