目录
一、终端字符颜色简介
二、在终端控制台实现输出彩色字体的软硬件条件
三、windows在终端输出彩色字体的方法
四、在终端输出彩色字体的语法
五、终端彩色字体例子
六、收集的一些终端输出彩色字体的解决方案
七、使用colorama第三方库输出彩色字体
终端的字符颜色是用转义序列控制的,是文本模式下的系统显示功能,和具体的语言无关。转义序列是以ESC开头,即用\033来完成(Escape的ASCII码用十进制表示是27,也就是十六进制0x1B,用八进制表示就是033。)
该种方法只限于控制台的输出改变颜色,不适用于生成的EXE文件的输出。
无条件支持的操作系统Linux
有条件支持的操作系统windows,条件:
获 取 控 制 台 模 式 |
|
支持的最低客户端 |
Windows 2000 Professional [仅限桌面应用程序] |
支持的最低服务器 |
Windows 2000 Server [仅限桌面应用程序] |
标题 |
ConsoleApi2.h(通过 WinCon.h,包括 Windows.h) |
Library |
Kernel32.lib |
DLL |
Kernel32.dll |
Unicode 和 ANSI 名称 |
WriteConsoleOutputCharacterW (Unicode) 和WriteConsoleOutputCharacterA (ANSI) |
使用ANSI转义序列。 10年前的Windows -控制台上不支持ANSI颜色 对于低于10的Windows版本,Windows命令控制台默认不支持输出着色。你可以安装Cmder, ConEmu, ANSICON或Mintty(在GitBash和Cygwin中默认使用)来添加着色支持到你的Windows命令控制台。 Windows 10 -命令行颜色 从Windows 10开始,Windows控制台默认支持ANSI转义序列和一些颜色。该功能于2015年11月随Threshold 2更新发布。 MSDN文档 更新(05-2019):ColorTool允许您更改控制台的配色方案。它是微软终端项目的一部分。 |
|
有些机器在aptana,idle,pycharm直接运行是不行的,需要使用cmd运行才能在终端正确通过print()输出彩色字体 |
|
参考:https://docs.microsoft.com/en-us/windows/console/writeconsoleoutputcharacter |
windows在终端通过print()输出彩色字体需要在代码里加入以下两行,Linux操作系统不用。
# -*- coding:utf-8 -*- import os os.system('') |
开头部分: |
内容 |
结尾部分: |
|||||||
\033 |
[ |
显示方式 |
; |
前景色 |
; |
背景色 |
m |
彩色字体显示内容 |
\033[0m |
参数见下表 |
参数见下表 |
参数见下表 |
|||||||
开头部分的三个参数:显示方式,前景色,背景色。 这三个参数是可选参数,可以只写其中的某一个,另外由于表示三个参数不同含义的数值都是唯一的没有重复的,所以三个单数的书写顺序没有固定的要求,但建议按照默认的格式规范书写。 |
结束这个格式的输出,如果没有加后面这段,后面不需要改变颜色的字符串输出,也会因为没有结束标志而变成彩色字 |
print()输出彩色字体———开头部分显示方式参数 |
|||||||||||
显示 方式 |
0 |
1 |
4 |
5 |
7 |
8 |
22 |
24 |
25 |
27 |
28 |
默认 |
高亮 |
下划线 |
闪烁 |
反白 |
不可见 |
非粗体 |
非下划线 |
非闪烁 |
非反显 |
可见 |
|
效果 |
终端 默认 |
高亮 显示 |
下划 线 |
闪烁 |
反白 显示 |
不可 见 |
非 粗体 |
非下 划线 |
非 闪烁 |
非 反显 |
可见 |
print()输出彩色字体———开头部分——前景色背景色参数 |
||||||||
颜色 |
黑色 |
红色 |
绿色 |
黄色 |
蓝色 |
品红色 |
青色 |
白色 |
前景颜色 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
背景颜色 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
print()输出彩色字体字体颜色与背景颜色搭配 |
||||||||
强度 |
0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
前景色 |
黑色 |
红色 |
绿色 |
黄色 |
蓝色 |
品红色 |
青色 |
白色 |
前景色明亮的 |
黑色 |
红色 |
绿色 |
黄色 |
蓝色 |
品红色 |
青色 |
白色 |
背景色 |
黑色 |
红色 |
绿色 |
黄色 |
蓝色 |
品红色 |
青色 |
白色 |
背景色明亮的 |
黑色 |
红色 |
绿色 |
黄色 |
蓝色 |
品红色 |
青色 |
白色 |
下划线 |
黑色 |
红色 |
绿色 |
黄色 |
蓝色 |
品红色 |
青色 |
白色 |
前景颜色值 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
背景颜色值 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
注意: |
Windows不完全支持ANSI代码,无论是通过系统调用还是模块。并不是所有的文本装饰都支持,尽管显示了明亮的颜色,但它们与常规颜色相同。 不同的console,每种颜色对应的实际RGB值可能有出入。不同的console可能不会完全支持所有功能。 有些机器在aptana,idle,pycharm直接运行是不行的,需要使用cmd运行才能在终端正确通过print()输出彩色字体 |
python在终端通过print()输出彩色字体 |
||
代 码 |
print('\033[0;30m逆境清醒虽然已经很笨,但仍希望坚持保持善良\033[0m') print('\033[1;31m逆境清醒虽然已经很笨,但仍希望坚持保持善良\033[0m') print('\033[4;32m逆境清醒虽然已经很笨,但仍希望坚持保持善良\033[0m') print('\033[5;33m逆境清醒虽然已经很笨,但仍希望坚持保持善良\033[0m') print('\033[7;34m逆境清醒虽然已经很笨,但仍希望坚持保持善良\033[0m') print('\033[8;35m逆境清醒虽然已经很笨,但仍希望坚持保持善良\033[0m') print('\033[1;36m逆境清醒虽然已经很笨,但仍希望坚持保持善良\033[0m') print('\033[1;37m逆境清醒虽然已经很笨,但仍希望坚持保持善良\033[0m') |
|
运行结果 |
逆境清醒虽然已经很笨,但仍希望坚持保持善良 逆境清醒虽然已经很笨,但仍希望坚持保持善良 逆境清醒虽然已经很笨,但仍希望坚持保持善良 逆境清醒虽然已经很笨,但仍希望坚持保持善良 逆境清醒虽然已经很笨,但仍希望坚持保持善良 逆境清醒虽然已经很笨,但仍希望坚持保持善良 逆境清醒虽然已经很笨,但仍希望坚持保持善良 逆境清醒虽然已经很笨,但仍希望坚持保持善良 |
|
对于结尾部分,其实也可以省略,只用开头部分+输入文字 执行效果(没有结束符号,整行都会有背景色) 建议语句最后还是加上\033[0m为恢复默认,否则下面的其他输出字体都会被影响 |
|
代 码 |
#-*- coding:utf-8 -*- print('\033[0m显示方式0\033[0m') print('\033[1m显示方式1\033[0m') print('\033[4m显示方式4\033[0m') print('\033[5m显示方式5\033[0m') print('\033[7m显示方式7\033[0m') print('\033[8m显示方式8\033[0m') print('\033[30m前景色0\033[0m') print('\033[31m前景色1\033[0m') print('\033[32m前景色2\033[0m') print('\033[33m前景色3\033[0m') print('\033[34m前景色4\033[0m') print('\033[35m前景色5\033[0m') print('\033[36m前景色6\033[0m') print('\033[37m前景色7\033[0m') print('\033[40m背景色0\033[0m') print('\033[41m背景色1\033[0m') print('\033[42m背景色2\033[0m') print('\033[43m背景色3\033[0m') print('\033[44m背景色4\033[0m') print('\033[45m背景色5\033[0m') print('\033[46m背景色6\033[0m') print('\033[47m背景色7\033[0m') |
运行结果 |
显示方式0 显示方式1 显示方式4 显示方式5 显示方式7 显示方式8 前景色0 前景色0 前景色1 前景色2 前景色3 前景色4 前景色5 前景色6 前景色7 背景色0 背景色1 背景色2 背景色3 背景色4 背景色5 背景色6 背景色7 |
代 码 |
print('\033[0;36m Adversity awake \033[0m') |
运行结果 |
Adversity awake |
代 码 |
# 若打印的不是字符串,而是变量值,则需要将变量值转为字符类型 a = 7472 print('\033[0;36m abc='+ str(a)+ '\033[0m') |
运行结果 |
a = 7472 |
代 码 |
#多行输出彩色字 print('\033[7;34m ') print('工作认真对待,') print('困难勇敢面对,') print('生活细细品味,') print('真情慢慢体会,') print('珍惜人生中每一次相识,') print('珍惜天地间每一分温暖,') print('珍惜每一个无声的默契,') print('不枉此生。') print(' \033[0m') |
运行结果 |
工作认真对待, 困难勇敢面对, 生活细细品味, 真情慢慢体会, 珍惜人生中每一次相识, 珍惜天地间每一分温暖, 珍惜每一个无声的默契, 不枉此生。 |
原作者名丢失,如果是您的作品,请在本文评论区留言,我会在文中补上您的署名和链接
这里有一个适用于Windows 10的解决方案。 使用系统调用,例如os.system(""),允许颜色在命令提示符和Powershell中本机打印: 这里有一个适用于Windows 10的解决方案。 |
import os # System call # Class of different styles print(style.YELLOW + "Hello, World!") |
This way we can create a full color collection: |
|
在IDLE里打印颜色字符 |
|
代 码 |
import sys try: shell = sys.stdout.shell except AttributeError: raise RuntimeError("you must run this program in IDLE") shell.write("Wanna go explore? ","KEYWORD") shell.write("OPTIONS","STRING") shell.write(" : ","KEYWORD") shell.write("Yes","DEFINITION") shell.write(" or ","KEYWORD") shell.write("No","COMMENT") print() print("here are all the valid tags:\n") valid_tags = ('SYNC', 'stdin', 'BUILTIN', 'STRING', 'console', 'COMMENT', 'stdout', 'TODO','stderr', 'hit', 'DEFINITION', 'KEYWORD', 'ERROR', 'sel') for tag in valid_tags: shell.write(tag+"\n",tag) |
win10colors.cmd |
|
代 码 |
@echo off cls echo [101;93m STYLES [0m echo ^ echo ^ echo ^ echo ^ echo. echo [101;93m NORMAL FOREGROUND COLORS [0m echo ^ echo ^ echo ^ echo ^ echo ^ echo ^ echo ^ echo ^ echo. echo [101;93m NORMAL BACKGROUND COLORS [0m echo ^ echo ^ echo ^ echo ^ echo ^ echo ^ echo ^ echo ^ echo. echo [101;93m STRONG FOREGROUND COLORS [0m echo ^ echo ^ echo ^ echo ^ echo ^ echo ^ echo ^ echo ^ echo. echo [101;93m STRONG BACKGROUND COLORS [0m echo ^ echo ^ echo ^ echo ^ echo ^ echo ^ echo ^ echo ^ echo. echo [101;93m COMBINATIONS [0m echo ^ echo ^ echo ^ echo ^ echo ^ |
这是一个自编译的bat/.net混合(应该保存为. bat),可以在任何安装了。net框架的系统上使用(即使是最老的XP/2003安装,也很少看到一个没有。net框架的窗口)。它使用jscript.net编译器创建一个exe,能够只打印当前行具有不同背景/前景颜色的字符串。 |
|
代 码 |
@if (@X)==(@Y) @end /* JScript comment @echo off setlocal for /f "tokens=* delims=" %%v in ('dir /b /s /a:-d /o:-n "%SystemRoot%\Microsoft.NET\Framework\*jsc.exe"') do ( set "jsc=%%v" ) if not exist "%~n0.exe" ( "%jsc%" /nologo /out:"%~n0.exe" "%~dpsfnx0" ) %~n0.exe %* endlocal & exit /b %errorlevel% */ import System; var arguments:String[] = Environment.GetCommandLineArgs(); var newLine = false; var output = ""; var foregroundColor = Console.ForegroundColor; var backgroundColor = Console.BackgroundColor; var evaluate = false; var currentBackground=Console.BackgroundColor; var currentForeground=Console.ForegroundColor; //http://stackoverflow.com/a/24294348/388389 var jsEscapes = { 'n': '\n', 'r': '\r', 't': '\t', 'f': '\f', 'v': '\v', 'b': '\b' }; function decodeJsEscape(_, hex0, hex1, octal, other) { var hex = hex0 || hex1; if (hex) { return String.fromCharCode(parseInt(hex, 16)); } if (octal) { return String.fromCharCode(parseInt(octal, 8)); } return jsEscapes[other] || other; } function decodeJsString(s) { return s.replace( // Matches an escape sequence with UTF-16 in group 1, single byte hex in group 2, // octal in group 3, and arbitrary other single-character escapes in group 4. /\\(?:u([0-9A-Fa-f]{4})|x([0-9A-Fa-f]{2})|([0-3][0-7]{0,2}|[4-7][0-7]?)|(.))/g, decodeJsEscape); } function printHelp( ) { print( arguments[0] + " -s string [-f foreground] [-b background] [-n] [-e]" ); print( " " ); print( " string String to be printed" ); print( " foreground Foreground color - a " ); print( " number between 0 and 15." ); print( " background Background color - a " ); print( " number between 0 and 15." ); print( " -n Indicates if a new line should" ); print( " be written at the end of the "); print( " string(by default - no)." ); print( " -e Evaluates special character " ); print( " sequences like \\n\\b\\r and etc "); print( "" ); print( "Colors :" ); for ( var c = 0 ; c < 16 ; c++ ) {
Console.BackgroundColor = c; Console.Write( " " ); Console.BackgroundColor=currentBackground; Console.Write( "-"+c ); Console.WriteLine( "" ); } Console.BackgroundColor=currentBackground;
} function errorChecker( e:Error ) { if ( e.message == "Input string was not in a correct format." ) { print( "the color parameters should be numbers between 0 and 15" ); Environment.Exit( 1 ); } else if (e.message == "Index was outside the bounds of the array.") { print( "invalid arguments" ); Environment.Exit( 2 ); } else { print ( "Error Message: " + e.message ); print ( "Error Code: " + ( e.number & 0xFFFF ) ); print ( "Error Name: " + e.name ); Environment.Exit( 666 ); } } function numberChecker( i:Int32 ){ if( i > 15 || i < 0 ) { print("the color parameters should be numbers between 0 and 15"); Environment.Exit(1); } } if ( arguments.length == 1 || arguments[1].toLowerCase() == "-help" || arguments[1].toLowerCase() == "-help" ) { printHelp(); Environment.Exit(0); } for (var arg = 1; arg <= arguments.length-1; arg++ ) { if ( arguments[arg].toLowerCase() == "-n" ) { newLine=true; }
if ( arguments[arg].toLowerCase() == "-e" ) { evaluate=true; }
if ( arguments[arg].toLowerCase() == "-s" ) { output=arguments[arg+1]; }
if ( arguments[arg].toLowerCase() == "-b" ) {
try { backgroundColor=Int32.Parse( arguments[arg+1] ); } catch(e) { errorChecker(e); } }
if ( arguments[arg].toLowerCase() == "-f" ) { try { foregroundColor=Int32.Parse(arguments[arg+1]); } catch(e) { errorChecker(e); } } } Console.BackgroundColor = backgroundColor ; Console.ForegroundColor = foregroundColor ; if ( evaluate ) { output=decodeJsString(output); } if ( newLine ) { Console.WriteLine(output); } else { Console.Write(output);
} Console.BackgroundColor = currentBackground; Console.ForegroundColor = currentForeground; |
一种可适用于EXE文件输出的方法。介绍资料来源于官网colorama开发者的介绍。
使用colorama第三方库输出
(一)、简介
使 ANSI 转义字符序列(用于生成彩色终端文本和光标定位)在 MS Windows 下工作。
安装在 CPython 2.7、3.5、3.6、3.7、3.8、3.9 和 3.10 以及 Pypy 2.7 和 3.6 上进行了测试。
除了标准库之外没有其他要求。
ANSI 转义字符序列长期以来一直用于在 Unix 和 Mac 上生成彩色终端文本和光标定位。Colorama 通过包装stdout、剥离它找到的 ANSI 序列(在输出中将显示为 gobbledygook )并将它们转换为适当的 win32 调用以修改终端的状态,也使这项工作在 Windows 上工作。在其他平台上,Colorama 什么都不做。
这样做的结果是提供了一个简单的跨平台 API 用于从 Python 打印彩色终端文本,并且具有令人愉快的副作用,即使用 ANSI 序列在 Linux 或 Mac 上生成彩色输出的现有应用程序或库现在也可以在 Windows 上运行,只需调用 colorama.init()即可。
另一种方法是在 Windows 机器上安装ansi.sys,它为在终端中运行的所有应用程序提供相同的行为。Colorama 适用于不容易实现的情况(例如,您的应用可能没有安装程序。)
源代码存储库中的演示脚本使用 ANSI 序列打印一些彩色文本。比较它们在 Gnome 终端的内置 ANSI 处理下的输出,与在 Windows 命令提示符下使用 Colorama 的输出:
这些屏幕截图显示,在 Windows 上,Colorama 不支持 ANSI 'dim text';它看起来与“普通文本”相同。
Python的Colorama模块,可以跨多终端,显示字体不同的颜色和背景,只需要导入colorama模块即可,不用再每次都像上方注释性语句一样记忆过多的参数;
(二)、安装
pip install colorama
# 或
conda install -c anaconda colorama
(三)、用法
初始化
应用程序应使用以下方法初始化 Colorama:
from colorama import init init() |
在 Windows 上,调用init()将从发送到stdout或stderr的任何文本中过滤掉 ANSI 转义序列,并将它们替换为等效的 Win32 调用。
在其他平台上,调用init()无效(除非您请求其他可选功能,请参阅下面的“初始化关键字参数”;或者如果输出被重定向)。按照设计,这允许应用程序在所有平台上无条件地调用init() ,之后 ANSI 输出应该正常工作。
在所有平台上,如果输出被重定向,ANSI 转义序列将被完全去除。
要在程序退出之前停止使用 Colorama,只需调用deinit()即可。这会将stdout和stderr恢复为其原始值,从而禁用 Colorama。要再次使用 Colorama,请调用reinit();它比再次调用init()便宜(但做同样的事情)。
彩色输出
然后可以使用 Colorama 的 ANSI 转义序列的常量简写来完成彩色文本的跨平台打印。这些是刻意的初级,见下文。
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') |
…或者简单地从您自己的代码中手动打印 ANSI 序列:
print('\033[31m' + 'some red text') print('\033[39m') #并重置为默认颜色 |
…或者,Colorama 可以与现有的 ANSI 库结合使用,例如古老的Termcolor 、神话般的Blessings或令人难以置信的_Rich。
如果您希望 Colorama 的 Fore、Back 和 Style 常量功能更强大,请考虑使用上述功能强大的库之一来生成颜色等,并仅将 Colorama 用于其主要目的:将这些 ANSI 序列转换为也适用于 Windows:
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')) |
#然后对所有彩色文本输出使用Termcolor _ _
可用的格式常量有:
前部:黑色、红色、绿色、黄色、蓝色、品红色、青色、白色、重置。
背面:黑色、红色、绿色、黄色、蓝色、品红色、青色、白色、重置。
风格:暗淡、正常、明亮、RESET_ALL
Style.RESET_ALL重置前景、背景和亮度。Colorama 将在程序退出时自动执行此重置。
这些得到了很好的支持,但不是标准的一部分:
前:LIGHTBLACK_EX、LIGHTRED_EX、LIGHTGREEN_EX、LIGHTYELLOW_EX、LIGHTBLUE_EX、LIGHTMAGENTA_EX、LIGHTCYAN_EX、LIGHTWHITE_EX 背面:LIGHTBLACK_EX、LIGHTRED_EX、LIGHTGREEN_EX、LIGHTYELLOW_EX、LIGHTBLUE_EX、LIGHTMAGENTA_EX、LIGHTCYAN_EX、LIGHTWHITE_EX |
光标定位
支持重新定位光标的 ANSI 代码。有关如何生成它们的示例,请参见demos/demo06.py 。
初始化关键字参数
init()接受一些**kwargs来覆盖默认行为。
初始化(自动重置=假):
如果您发现自己在每次打印结束时重复发送重置序列以关闭颜色更改,那么init(autoreset=True)将自动执行以下操作:
from colorama import init init(autoreset=True) print(Fore.RED + 'some red text') print('automatically back to default color again') |
初始化(条=无):
传递True或False以覆盖是否应从输出中去除 ANSI 代码。如果在 Windows 上或输出被重定向(不是 tty),默认行为是剥离。
初始化(转换=无):
传递True或False以覆盖是否将输出中的 ANSI 代码转换为 win32 调用。默认行为是在 Windows 上转换 if 并且输出到 tty(终端)。
初始化(包装=真):
在 Windows 上,Colorama 通过将sys.stdout和sys.stderr替换 为代理对象来工作,这些代理对象会覆盖.write()方法来完成它们的工作。如果这种包装给你带来了问题,那么可以通过传递 init(wrap=False)来禁用它。如果autoreset或 strip或convert为 True ,则默认行为是换行。
禁用环绕后,非 Windows 平台上的彩色打印将继续正常工作。要进行跨平台彩色输出,可以直接使用 Colorama 的AnsiToWin32代理:
import sys from colorama import init, AnsiToWin32 init(wrap=False) stream = AnsiToWin32(sys.stderr).stream # Python 2 print >>stream, Fore.BLUE + 'blue text on stderr' # Python 3 print(Fore.BLUE + 'blue text on stderr', file=stream) |
公认的 ANSI 序列
ANSI 序列通常采用以下形式:
ESC [ <参数> ; <参数> ... <命令>
其中是一个整数,而
Colorama 转换为 win32 调用的唯一 ANSI 序列是:
ESC [ 0 m # reset all (colors and brightness) ESC [ 1 m # bright ESC [ 2 m # dim (looks same as normal brightness) ESC [ 22 m # normal brightness # FOREGROUND: ESC [ 30 m # black ESC [ 31 m # red ESC [ 32 m # green ESC [ 33 m # yellow ESC [ 34 m # blue ESC [ 35 m # magenta ESC [ 36 m # cyan ESC [ 37 m # white ESC [ 39 m # reset # BACKGROUND ESC [ 40 m # black ESC [ 41 m # red ESC [ 42 m # green ESC [ 43 m # yellow ESC [ 44 m # blue ESC [ 45 m # magenta ESC [ 46 m # cyan ESC [ 47 m # white ESC [ 49 m # reset # cursor positioning ESC [ y;x H # position cursor at x across, y down ESC [ y;x f # position cursor at x across, y down ESC [ n A # move cursor n lines up ESC [ n B # move cursor n lines down ESC [ n C # move cursor n characters forward ESC [ n D # move cursor n characters backward # clear the screen ESC [ mode J # clear the screen # clear the line ESC [ mode K # clear the line |
'm'命令的多个数字参数可以组合成一个序列:
ESC [ 36 ; 45; 1 m # 洋红色背景上的亮青色文本
ESC [ ;形式的所有其他 ANSI 序列 ...
任何其他形式的 ANSI 序列,例如单字符代码或替代初始字符,都不会被识别或去除。不过添加它们会很酷。
状态和已知问题
colorama开发者个人在 Windows XP(CMD、Console2)、Ubuntu(gnome-terminal、xterm)和 OS X 上测试过它。
10 | ![]() |
9 | matplotlib 自带绘图样式效果展示速查(全) |
8 | 手机屏幕坏了____怎么把里面的资料导出(18种方法) |
7 | 2022年7月多家权威机构____编程语言排行榜__薪酬状况 |
6 | Python中Print()函数的用法___详解(全,例多) |
5 | 色彩颜色对照表系列(1~5)(16进制、RGB、CMYK、HSV、中英文名) |
4 | Tomcat端口配置(详细) |
3 | Tomcat 启动闪退问题解决集(八大类详细) |
2 | Apache Tomcat 各版本发行时间( v10.1.0-M17~v3.0) |
1 | Tomcat10安装(Windows环境)(详细) |