Java 如何为 System.out.println 输出着色?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1448858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to color System.out.println output?
提问by Davide Aversa
How can I color Java output?
如何为 Java 输出着色?
For example in C and other languages I can use ANSI-escape like \033[0m
to do this. But in Java it doesn't work.
例如在 C 和其他语言中,我可以使用 ANSI-escape\033[0m
来做到这一点。但是在Java中它不起作用。
public static void main(String[] x) {
System.out.println("3[0m BLABLA 3[0m\n");
}
采纳答案by Jonas B
No, but there are third party API's that can handle it
不,但有第三方 API 可以处理它
http://www.javaworld.com/javaworld/javaqa/2002-12/02-qa-1220-console.html
http://www.javaworld.com/javaworld/javaqa/2002-12/02-qa-1220-console.html
Edit: of course there are newer articles than that one I posted, the information is still viable though.
编辑:当然还有比我发布的文章更新的文章,但这些信息仍然可用。
回答by Thorbj?rn Ravn Andersen
Escape sequences must be interpreted by SOMETHING to be converted to color. The standard CMD.EXE used by java when started from the command line, doesn't support this so therefore Java does not.
转义序列必须由某些东西解释才能转换为颜色。从命令行启动时,java 使用的标准 CMD.EXE 不支持此功能,因此 Java 不支持。
回答by kevinarpe
Here is a solution for Win32 Console.
这是 Win32 控制台的解决方案。
1) Get JavaNativeAccess libraries here: https://github.com/twall/jna/
1) 在此处获取 JavaNativeAccess 库:https: //github.com/twall/jna/
2) These two Java classes will do the trick.
2) 这两个 Java 类可以解决问题。
Enjoy.
享受。
package com.stackoverflow.util;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
import com.sun.jna.Structure;
public class Win32 {
public static final int STD_INPUT_HANDLE = -10;
public static final int STD_OUTPUT_HANDLE = -11;
public static final int STD_ERROR_HANDLE = -12;
public static final short CONSOLE_FOREGROUND_COLOR_BLACK = 0x00;
public static final short CONSOLE_FOREGROUND_COLOR_BLUE = 0x01;
public static final short CONSOLE_FOREGROUND_COLOR_GREEN = 0x02;
public static final short CONSOLE_FOREGROUND_COLOR_AQUA = 0x03;
public static final short CONSOLE_FOREGROUND_COLOR_RED = 0x04;
public static final short CONSOLE_FOREGROUND_COLOR_PURPLE = 0x05;
public static final short CONSOLE_FOREGROUND_COLOR_YELLOW = 0x06;
public static final short CONSOLE_FOREGROUND_COLOR_WHITE = 0x07;
public static final short CONSOLE_FOREGROUND_COLOR_GRAY = 0x08;
public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_BLUE = 0x09;
public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_GREEN = 0x0A;
public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_AQUA = 0x0B;
public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_RED = 0x0C;
public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_PURPLE = 0x0D;
public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_YELLOW = 0x0E;
public static final short CONSOLE_FOREGROUND_COLOR_BRIGHT_WHITE = 0x0F;
public static final short CONSOLE_BACKGROUND_COLOR_BLACK = 0x00;
public static final short CONSOLE_BACKGROUND_COLOR_BLUE = 0x10;
public static final short CONSOLE_BACKGROUND_COLOR_GREEN = 0x20;
public static final short CONSOLE_BACKGROUND_COLOR_AQUA = 0x30;
public static final short CONSOLE_BACKGROUND_COLOR_RED = 0x40;
public static final short CONSOLE_BACKGROUND_COLOR_PURPLE = 0x50;
public static final short CONSOLE_BACKGROUND_COLOR_YELLOW = 0x60;
public static final short CONSOLE_BACKGROUND_COLOR_WHITE = 0x70;
public static final short CONSOLE_BACKGROUND_COLOR_GRAY = 0x80;
public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_BLUE = 0x90;
public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_GREEN = 0xA0;
public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_AQUA = 0xB0;
public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_RED = 0xC0;
public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_PURPLE = 0xD0;
public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_YELLOW = 0xE0;
public static final short CONSOLE_BACKGROUND_COLOR_BRIGHT_WHITE = 0xF0;
// typedef struct _COORD {
// SHORT X;
// SHORT Y;
// } COORD, *PCOORD;
public static class COORD extends Structure {
public short X;
public short Y;
}
// typedef struct _SMALL_RECT {
// SHORT Left;
// SHORT Top;
// SHORT Right;
// SHORT Bottom;
// } SMALL_RECT;
public static class SMALL_RECT extends Structure {
public short Left;
public short Top;
public short Right;
public short Bottom;
}
// typedef struct _CONSOLE_SCREEN_BUFFER_INFO {
// COORD dwSize;
// COORD dwCursorPosition;
// WORD wAttributes;
// SMALL_RECT srWindow;
// COORD dwMaximumWindowSize;
// } CONSOLE_SCREEN_BUFFER_INFO;
public static class CONSOLE_SCREEN_BUFFER_INFO extends Structure {
public COORD dwSize;
public COORD dwCursorPosition;
public short wAttributes;
public SMALL_RECT srWindow;
public COORD dwMaximumWindowSize;
}
// Source: https://github.com/twall/jna/nonav/javadoc/index.html
public interface Kernel32 extends Library {
Kernel32 DLL = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class);
// HANDLE WINAPI GetStdHandle(
// __in DWORD nStdHandle
// );
public int GetStdHandle(
int nStdHandle);
// BOOL WINAPI SetConsoleTextAttribute(
// __in HANDLE hConsoleOutput,
// __in WORD wAttributes
// );
public boolean SetConsoleTextAttribute(
int in_hConsoleOutput,
short in_wAttributes);
// BOOL WINAPI GetConsoleScreenBufferInfo(
// __in HANDLE hConsoleOutput,
// __out PCONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo
// );
public boolean GetConsoleScreenBufferInfo(
int in_hConsoleOutput,
CONSOLE_SCREEN_BUFFER_INFO out_lpConsoleScreenBufferInfo);
// DWORD WINAPI GetLastError(void);
public int GetLastError();
}
}
package com.stackoverflow.util;
import java.io.PrintStream;
import com.stackoverflow.util.Win32.Kernel32;
public class ConsoleUtil {
public static void main(String[] args)
throws Exception {
System.out.print("abc");
static_color_print(
System.out,
"def",
Win32.CONSOLE_BACKGROUND_COLOR_RED,
Win32.CONSOLE_FOREGROUND_COLOR_BRIGHT_WHITE);
System.out.print("def");
System.out.println();
}
private static Win32.CONSOLE_SCREEN_BUFFER_INFO _static_console_screen_buffer_info = null;
public static void static_save_settings() {
if (null == _static_console_screen_buffer_info) {
_static_console_screen_buffer_info = new Win32.CONSOLE_SCREEN_BUFFER_INFO();
}
int stdout_handle = Kernel32.DLL.GetStdHandle(Win32.STD_OUTPUT_HANDLE);
Kernel32.DLL.GetConsoleScreenBufferInfo(stdout_handle, _static_console_screen_buffer_info);
}
public static void static_restore_color()
throws Exception {
if (null == _static_console_screen_buffer_info) {
throw new Exception("Internal error: Must save settings before restore");
}
int stdout_handle = Kernel32.DLL.GetStdHandle(Win32.STD_OUTPUT_HANDLE);
Kernel32.DLL.SetConsoleTextAttribute(
stdout_handle,
_static_console_screen_buffer_info.wAttributes);
}
public static void static_set_color(Short background_color, Short foreground_color) {
int stdout_handle = Kernel32.DLL.GetStdHandle(Win32.STD_OUTPUT_HANDLE);
if (null == background_color || null == foreground_color) {
Win32.CONSOLE_SCREEN_BUFFER_INFO console_screen_buffer_info =
new Win32.CONSOLE_SCREEN_BUFFER_INFO();
Kernel32.DLL.GetConsoleScreenBufferInfo(stdout_handle, console_screen_buffer_info);
short current_bg_and_fg_color = console_screen_buffer_info.wAttributes;
if (null == background_color) {
short current_bg_color = (short) (current_bg_and_fg_color / 0x10);
background_color = new Short(current_bg_color);
}
if (null == foreground_color) {
short current_fg_color = (short) (current_bg_and_fg_color % 0x10);
foreground_color = new Short(current_fg_color);
}
}
short bg_and_fg_color =
(short) (background_color.shortValue() | foreground_color.shortValue());
Kernel32.DLL.SetConsoleTextAttribute(stdout_handle, bg_and_fg_color);
}
public static<T> void static_color_print(
PrintStream ostream,
T value,
Short background_color,
Short foreground_color)
throws Exception {
static_save_settings();
try {
static_set_color(background_color, foreground_color);
ostream.print(value);
}
finally {
static_restore_color();
}
}
public static<T> void static_color_println(
PrintStream ostream,
T value,
Short background_color,
Short foreground_color)
throws Exception {
static_save_settings();
try {
static_set_color(background_color, foreground_color);
ostream.println(value);
}
finally {
static_restore_color();
}
}
}
回答by MrDrews
回答by dialex
I created a jar
library called JCDP(Java Colored Debug Printer).
我创建了一个jar
名为JCDP(Java 彩色调试打印机)的库。
For Linux it uses the ANSI escape codes that WhiteFang mentioned, but abstracts them using words instead of codes which is much more intuitive.
对于 Linux,它使用 WhiteFang 提到的 ANSI 转义码,但使用单词而不是更直观的代码将它们抽象出来。
For Windows it actually includes the JAnsi library but creates an abstraction layer over it, maintaining the intuitive and simple interface created for Linux.
对于 Windows,它实际上包含 JAnsi 库,但在其上创建了一个抽象层,维护了为 Linux 创建的直观和简单的界面。
This library is licensed under the MIT Licenseso feel free to use it.
Have a look at JCDP's github repository.
回答by user222202
The simplest method is to run your program (unmodified) in Cygwin console.
最简单的方法是在 Cygwin 控制台中运行您的程序(未修改)。
The second simplest method is to run you program (also unmodified) in the ordinary Windows console, pipelining its output through tee.exe (from Cygwin or Git distribution). Tee.exe will recognize the escape codes and call appropriate WinAPI functions.
第二种最简单的方法是在普通的 Windows 控制台中运行您的程序(也未修改),通过 tee.exe(来自 Cygwin 或 Git 发行版)将其输出流水线化。Tee.exe 将识别转义码并调用适当的 WinAPI 函数。
Something like:
就像是:
java MyClass | tee.exe log.txt
java MyClass | tee.exe /dev/null
回答by Raman
Yes it is 100% possible
是的,100% 可能
set classpath= %classpath%;d:\jansi-1.4.jar;
设置类路径= %classpath%;d:\jansi-1.4.jar;
Try this below code:
试试下面的代码:
import org.fusesource.jansi.AnsiConsole;
import static org.fusesource.jansi.Ansi.*;
import static org.fusesource.jansi.Ansi.Color.*;
public class Sample
{
public static void main(String[] args)
{
AnsiConsole.systemInstall();
System.out.println(ansi().fg(RED).a("Hello World").reset());
System.out.println("My Name is Raman");
AnsiConsole.systemUninstall();
}
}
回答by dylnmc
Note
笔记
You may not be able to color Window's cmd prompt
, but it should work in many unix (or unix-like) terminals.
您可能无法为 Window 着色cmd prompt
,但它应该可以在许多 unix(或类 unix)终端中使用。
Also, note that some terminals simply won't support some (if any) ANSI escape sequences and, especially, 24-bit colors.
另请注意,某些终端根本不支持某些(如果有)ANSI 转义序列,尤其是 24 位颜色。
Usage
用法
Please refer to the section Cursesat the bottom for the best solution. For a personal or easy solution (although notas cross-platform solution), refer to the ANSI Escape Sequencessection.
请参阅底部的诅咒部分以获得最佳解决方案。对于个人或简单的解决方案(虽然不是跨平台解决方案),请参阅ANSI 转义序列部分。
TL;DR
TL; 博士
java:
System.out.println((char)27 + "[31m" + "ERROR MESSAGE IN RED");
python:
print(chr(27) + "[31m" + "ERROR MESSAGE IN RED")
- bashor zsh:
printf '\x1b[31mERROR MESSAGE IN RED'
- this may also work for Os X:
printf '\e[31mERROR MESSAGE IN RED'
- this may also work for Os X:
- sh:
printf '
CTRL+V,CTRL+[[31mERROR MESSAGE IN RED'
- ie, press CTRL+Vand then CTRL+[in order to get a "raw" ESCcharacter when escape interpretation is not available
- If done correctly, you should see a
^[
. Although it looks like two characters, it is really just one, the ESCcharacter. - You can also press CTRL+V,CTRL+[in vimin any of the programming or sripting langauges because that uses a literal ESCcharacter
- Also, you can replace Ctrl+[with ESC… eg, you can use CTRL+V,ESC, but I find the former easier, since I am already pressing CTRLand since [is less out of the way.
爪哇:
System.out.println((char)27 + "[31m" + "ERROR MESSAGE IN RED");
蟒蛇:
print(chr(27) + "[31m" + "ERROR MESSAGE IN RED")
- bash或zsh:
printf '\x1b[31mERROR MESSAGE IN RED'
- 这也适用于 OS X:
printf '\e[31mERROR MESSAGE IN RED'
- 这也适用于 OS X:
- sh:
printf '
CTRL+ V, CTRL+[[31mERROR MESSAGE IN RED'
- 即,当转义解释不可用时,按CTRL+V然后按CTRL+ [以获得“原始”ESC字符
- 如果操作正确,您应该会看到一个
^[
. 虽然看起来像两个角色,但实际上只是一个ESC角色。 - 您还可以在任何编程或脚本语言中的vim中按CTRL+ V, CTRL+ [,因为它使用文字字符ESC
- 另外,你可以用...替换Ctrl+ [,ESC例如,你可以使用CTRL+ V, ESC,但我发现前者更容易,因为我已经按下了CTRL,因为[它不那么碍手碍脚。
ANSI Escape Sequences
ANSI 转义序列
Background on Escape Sequences
转义序列的背景
While it is not the best way to do it, the easiest way to do this in a programming or scripting language is to use escape sequences. From that link:
虽然这不是最好的方法,但在编程或脚本语言中最简单的方法是使用转义序列。从该链接:
An escape sequence is a series of characters used to change the state of computers and their attached peripheral devices. These are also known as control sequences, reflecting their use in device control.
转义序列是一系列字符,用于更改计算机及其连接的外围设备的状态。这些也称为控制序列,反映了它们在设备控制中的用途。
Backgound on ANSI Escape Sequences
ANSI 转义序列的背景
However, it gets even easier than that in video text terminals, as these terminals use ANSI escape sequences. From that link:
然而,它比视频文本终端更容易,因为这些终端使用ANSI 转义序列。从该链接:
ANSI escape sequences are a standard for in-band signaling to control the cursor location, color, and other options on video text terminals. Certain sequences of bytes, most starting with Esc and '[', are embedded into the text, which the terminal looks for and interprets as commands, not as character codes.
ANSI 转义序列是带内信令的标准,用于控制视频文本终端上的光标位置、颜色和其他选项。某些字节序列(大多数以 Esc 和 '[' 开头)被嵌入到文本中,终端会查找这些文本并将其解释为命令,而不是字符代码。
How to Use ANSI Escape Sequences
如何使用 ANSI 转义序列
Generally
一般来说
- Escape sequences begin with an escape character; for ANSI escape sequences, the sequence always begins with ESC(ASCII:
27
/ hex:0x1B
). - For a list of what you can do, refer to the ANSI Escape Sequence List on Wikipedia
- 转义序列以转义字符开头;对于 ANSI 转义序列,该序列始终以ESC(ASCII:
27
/ hex:0x1B
)开头。 - 有关您可以执行的操作的列表,请参阅维基百科上的ANSI 转义序列列表
In Programming Languages
在编程语言中
Some programming langauges (like Java) will not interpret \e
or \x1b
as the ESCcharacter. However, we know that the ASCII character 27
isthe ESCcharacter, so we can simply typecast 27
to a char
and use that to begin the escape sequence.
一些编程语言(如 Java)不会解释\e
或\x1b
作为ESC字符。然而,我们知道,ASCII字符27
是该ESC字符,所以我们可以简单的类型转换27
到char
并用它来开始转义序列。
Here are some ways to do it in common programming languages:
以下是一些常用编程语言中的方法:
Java
System.out.println((char)27 + "[33mYELLOW");
Python 3
print(chr(27) + "[34mBLUE");
print("\x1b[35mMAGENTA");
- Note that
\x1b
is interpretted correctly in python
- Note that
Node JS
- The following will NOTcolor output in JavaScript in the Web Console
console.log(String.fromCharCode(27) + "[36mCYAN");
console.log("\x1b[30;47mBLACK_ON_WHITE");
- Note that
\x1b
also works in node
- Note that
爪哇
System.out.println((char)27 + "[33mYELLOW");
蟒蛇 3
print(chr(27) + "[34mBLUE");
print("\x1b[35mMAGENTA");
- 请注意,
\x1b
在python中正确解释
- 请注意,
节点JS
- 以下内容不会在 Web 控制台的 JavaScript 中输出颜色
console.log(String.fromCharCode(27) + "[36mCYAN");
console.log("\x1b[30;47mBLACK_ON_WHITE");
- 请注意,这
\x1b
也适用于节点
- 请注意,这
In Shell Prompt OR Scripts
在 Shell 提示或脚本中
If you are working with bashor zsh, it is quite easy to color the output (in most terminals). In Linux, Os X, and in some Window's terminals, you can check to see if your terminal supports color by doing both of the following:
如果您正在使用bash或zsh,则很容易为输出着色(在大多数终端中)。在 Linux、Os X 和某些 Window 的终端中,您可以通过执行以下两项操作来检查您的终端是否支持颜色:
printf '\e[31mRED'
printf '\x1b[31mRED'
printf '\e[31mRED'
printf '\x1b[31mRED'
If you see color for both, then that's great! If you see color for only one, then use that sequence. If you do not see color for either of them, then double check to make sure you typed everything correctly and that you are in bash or zsh; if you still do not see any color, then your terminal probably does not support ANSI escape sequences.
如果您看到两者都有颜色,那就太好了!如果您只看到一种颜色,则使用该序列。如果您没有看到它们中的任何一个的颜色,请仔细检查以确保您正确输入了所有内容并且您使用的是 bash 或 zsh;如果您仍然看不到任何颜色,那么您的终端可能不支持 ANSI 转义序列。
If I recall correctly, linux terminals tend to support both \e
and \x1b
escape sequences, while os x terminals only tend to support \e
, but I may be wrong. Nonetheless, if you see something like the following image, then you're all set! (Note that I am using the shell, zsh, and it is coloring my prompt string; also, I am using urxvtas my terminal in linux.)
如果我没记错的话,linux 终端倾向于同时支持\e
和\x1b
转义序列,而 os x 终端只倾向于支持\e
,但我可能错了。尽管如此,如果您看到类似于下图的内容,那么您就大功告成了!(请注意,我正在使用 shell,zsh,并且它正在为我的提示字符串着色;此外,我在 linux 中使用urxvt作为我的终端。)
"How does this work?"you might ask. Bascially, printf
is interpretting the sequence of characters that follows (everything inside of the single-quotes). When printf
encounters \e
or \x1b
, it will convert these characters to the ESCcharacter (ASCII: 27). That's just what we want. Now, printf
sends ESC31m
, and since there is an ESCfollowed by a valid ANSI escape sequence, we should get colored output (so long as it is supported by the terminal).
“这是如何运作的?” 你可能会问。基本上,printf
是解释后面的字符序列(单引号内的所有内容)。当printf
遇到\e
或 时\x1b
,它会将这些字符转换为ESC字符(ASCII:27)。这正是我们想要的。现在,printf
发送ESC31m
,并且因为有一个ESC后跟有效的ANSI转义序列,我们应该获得彩色输出(只要它是由终端支持)。
You can also use echo -e '\e[32mGREEN'
(for example), to color output. Note that the -e
flag for echo
"[enables] interpretation of backslash escapes"and must be used if you want echo
to appropriately interpret the escape sequence.
您还可以使用echo -e '\e[32mGREEN'
(例如)对输出进行着色。请注意,如果您想适当地解释转义序列,则必须使用“[启用] 反斜杠转义解释”-e
标志。echo
echo
More on ANSI Escape Sequences
更多关于 ANSI 转义序列
ANSI escape sequences can do more than just color output, but let's start with that, and see exactly how color works; then, we will see how to manipulate the cursor; finally, we'll take a look and see how to use 8-bit color and also 24-bit color (although it only has tenuous support).
ANSI 转义序列可以做的不仅仅是颜色输出,但让我们从它开始,看看颜色是如何工作的;然后,我们将看到如何操作光标;最后,我们将看看如何使用 8 位颜色和 24 位颜色(尽管它只有微弱的支持)。
On Wikipedia, they refer to ESC[as CSI
, so I will do the same.
在维基百科上,他们指的ESC[是CSI
,所以我也会这样做。
Color
颜色
To color output using ANSI escapes, use the following:
要使用 ANSI 转义符为输出着色,请使用以下命令:
CSI
n
m
CSI
: escape character—^[[
or ESC[n
: a number—one of the following:30
-37
,39
: foreground40
-47
,49
: background
m
: a literal ASCIIm
—terminates the escape sequence
CSI
n
m
CSI
: 转义字符——^[[
或ESC[n
:一个数字——以下之一:30
-37
,39
: 前景40
-47
,49
: 背景
m
: 一个文字 ASCII —m
终止转义序列
I will use bash or zsh to demonstrate all of the possible color combinations. Plop the following in bash or zsh to see for yourself (You may need to replace \e
with \x1b
):
我将使用 bash 或 zsh 来演示所有可能的颜色组合。将以下内容放入 bash 或 zsh 中以亲自查看(您可能需要替换\e
为\x1b
):
for fg in {30..37} 39; do for bg in {40..47} 49; do printf "\e[${fg};${bg}m~TEST~"; done; printf "\n"; done;
for fg in {30..37} 39; do for bg in {40..47} 49; do printf "\e[${fg};${bg}m~TEST~"; done; printf "\n"; done;
Result:
结果:
Quick Reference (Color)
快速参考(颜色)
+~~~~~~+~~~~~~+~~~~~~~~~~~+
| fg | bg | color |
+~~~~~~+~~~~~~+~~~~~~~~~~~+
| 30 | 40 | black |
| 31 | 41 | red |
| 32 | 42 | green |
| 33 | 43 | yellow |
| 34 | 44 | blue |
| 35 | 45 | magenta |
| 36 | 46 | cyan |
| 37 | 47 | white |
| 39 | 49 | default |
+~~~~~~+~~~~~~+~~~~~~~~~~~+
Select Graphic Rendition (SGR)
选择图形再现 (SGR)
SGR just allows you to change the text. Many of these do not work in certain terminals, so use these sparingly in production-level projects. However, they can be useful for making program output more readable or helping you distinguish between different types of output.
SGR 只允许您更改文本。其中许多在某些终端中不起作用,因此在生产级项目中谨慎使用它们。但是,它们对于使程序输出更具可读性或帮助您区分不同类型的输出非常有用。
Color actually falls under SGR, so the syntax is the same:
颜色实际上属于 SGR,所以语法是相同的:
CSI
n
m
CSI
: escape character—^[[
or ESC[n
: a number—one of the following:0
: reset1
-9
: turns on various text effects21
-29
: turns off various text effects (less supported than1
-9
)30
-37
,39
: foreground color40
-47
,49
: background color38
: 8- or 24-bit foreground color (see 8/24-bit Colorbelow)48
: 8- or 24-bit background color (see 8/24-bit Colorbelow)
m
: a literal ASCIIm
—terminates the escape sequence
CSI
n
m
CSI
: 转义字符——^[[
或ESC[n
:一个数字——以下之一:0
: 重启1
-9
: 开启各种文字效果21
-29
: 关闭各种文字效果(比1
-支持的少9
)30
-37
,39
: 前景色40
-47
,49
: 背景色38
:8 位或 24 位前景色(参见下面的 8/24 位颜色)48
: 8 位或 24 位背景色(参见下面的 8/24 位颜色)
m
: 一个文字 ASCII —m
终止转义序列
Although there is only tenuous support for faint (2), italic (3), underline (4), blinking (5,6), reverse video (7), conceal (8), and crossed out (9), some (but rarely all) tend to work on linux and os x terminals.
虽然对微弱 (2)、斜体 (3)、下划线 (4)、闪烁 (5,6)、反向视频 (7)、隐藏 (8) 和划掉 (9) 仅有微弱的支持,但有些(但很少全部)倾向于在 linux 和 os x 终端上工作。
It's also worthwhile to note that you can separate any of the above attributes with a semi-colon. For example printf '\e[34;47;1;3mCRAZY TEXT\n'
will show CRAZY TEXT
with a blue foreground
on a white background
, and it will be bold
and italic
.
还值得注意的是,您可以用分号分隔上述任何属性。例如printf '\e[34;47;1;3mCRAZY TEXT\n'
将CRAZY TEXT
在 ablue foreground
上显示,white background
它将是bold
and italic
。
Eg:
例如:
Plop the following in your bash or zsh shell to see all of the text effects you can do. (You may need to replace \e
with \x1b
.)
在您的 bash 或 zsh shell 中输入以下内容以查看您可以执行的所有文本效果。(您可能需要替换\e
为\x1b
。)
for i in {1..9}; do printf "\e[${i}m~TEST~\e[0m "; done
for i in {1..9}; do printf "\e[${i}m~TEST~\e[0m "; done
Result:
结果:
You can see that my terminal supports all of the text effects exceptfor faint(2), conceal(8) and cross out(9).
你可以看到,我的终端支持所有的文字效果,除了为昏(2),隐藏(8)和划掉(9)。
Quick Reference (SGR Attributes 0-9)
快速参考(SGR 属性 0-9)
+~~~~~+~~~~~~~~~~~~~~~~~~+
| n | effect |
+~~~~~+~~~~~~~~~~~~~~~~~~+
| 0 | reset |
| 1 | bold |
| 2 | faint* |
| 3 | italic** |
| 4 | underline |
| 5 | slow blink |
| 6 | rapid blink* |
| 7 | inverse |
| 8 | conceal* |
| 9 | strikethrough* |
+~~~~~+~~~~~~~~~~~~~~~~~~+
* not widely supported
** not widely supported and sometimes treated as inverse
8-bit Color
8 位彩色
While most terminals support this, it is less supported than 0-7
,9
colors.
虽然大多数终端都支持这一点,但它的支持不如0-7
,9
颜色。
Syntax:
句法:
CSI
38;5;
n
m
CSI
: escape character—^[[
or ESC[38;5;
: literal string that denotes use of 8-bit colors for foregroundn
: a number—one of the following:0
-255
CSI
38;5;
n
m
CSI
: 转义字符——^[[
或ESC[38;5;
: 表示使用 8 位颜色作为前景的文字字符串n
:一个数字——以下之一:0
——255
If you want to preview all of the colors in your terminal in a nice way, I have a nice script on gist.github.com.
如果你想以一种很好的方式预览终端中的所有颜色,我在 gist.github.com 上有一个很好的脚本。
It looks like this:
它看起来像这样:
If you want to change the background using 8-bit colors, just replace the 38
with a 48
:
如果要使用 8 位颜色更改背景,只需将 替换38
为48
:
CSI
48;5;
n
m
CSI
: escape character—^[[
or ESC[48;5;
: literal string that denotes use of 8-bit colors for backgroundn
: a number—one of the following:0
-255
CSI
48;5;
n
m
CSI
: 转义字符——^[[
或ESC[48;5;
: 表示使用 8 位颜色作为背景的文字字符串n
:一个数字——以下之一:0
——255
24-bit Color
24 位彩色
Also known as true color, 24-bit color provides some really cool functionality. Support for this is definitely growing (as far as I know it works in most modern terminals except urxvt, my terminal [insert angry emoji]).
也称为真彩色,24 位彩色提供了一些非常酷的功能。对此的支持肯定会增加(据我所知,它适用于大多数现代终端,除了urxvt,我的终端 [插入愤怒的表情符号])。
24-bit color is actually supported in vim (see the vim wikito see how to enable 24-bit colors). It's really neat because it pulls from the colorscheme defined for gvim; eg, it uses the fg/bg from highlight guibg=#______ guifg=#______
for the 24-bit colors! Neato, huh?
vim 实际上支持 24 位颜色(请参阅vim wiki以了解如何启用 24 位颜色)。它真的很简洁,因为它来自为 gvim 定义的颜色方案;例如,它使用 fg/bg 来自highlight guibg=#______ guifg=#______
24 位颜色!尼托吧?
Here is how 24-bit color works:
以下是 24 位颜色的工作原理:
CSI
38;2;
r
;
g
;
b
m
CSI
: escape character—^[[
or ESC[38;2;
: literal string that denotes use of 24-bit colors for foregroundr
,g
,b
: numbers—each should be0
-255
CSI
38;2;
r
;
g
;
b
m
CSI
: 转义字符——^[[
或ESC[38;2;
: 表示前景使用 24 位颜色的文字字符串r
,g
,b
: 数字——每个都应该是0
-255
To test just a fewof the many colors you can have ((2^8)^3
or 2^24
or 16777216
possibilites, I think), you can use this in bash or zsh:
要测试您可以拥有的多种颜色中的几种((2^8)^3
或2^24
或16777216
可能的,我认为),您可以在 bash 或 zsh 中使用它:
for r in 0 127 255; do for g in 0 127 255; do for b in 0 127 255; do printf "\e[38;2;${r};${g};${b}m($r,$g,$b)\e[0m "; done; printf "\n"; done; done;
for r in 0 127 255; do for g in 0 127 255; do for b in 0 127 255; do printf "\e[38;2;${r};${g};${b}m($r,$g,$b)\e[0m "; done; printf "\n"; done; done;
Result (this is in gnome-terminalsince urxvtDOES NOT SUPPORT 24-bit color... get it together, urxvt maintainer ... for real):
结果(这是在gnome-terminal 中,因为urxvt不支持 24 位颜色......把它放在一起,urxvt 维护者......真的):
If you want 24-bit colors for the background ... you guessed it! You just replace 38
with 48
:
如果您想要 24 位颜色的背景……您猜对了!您只需替换38
为48
:
CSI
48;2;
r
;
g
;
b
m
CSI
: escape character—^[[
or ESC[48;2;
: literal string that denotes use of 24-bit colors for backgroundr
,g
,b
: numbers—each should be0
-255
CSI
48;2;
r
;
g
;
b
m
CSI
: 转义字符——^[[
或ESC[48;2;
: 表示使用 24 位颜色作为背景的文字字符串r
,g
,b
: 数字——每个都应该是0
-255
Inserting Raw Escape Sequences
插入原始转义序列
Sometimes \e
and \x1b
will not work. For example, in the shshell, sometimes neither works (although it does on my system now, I don't think it used to).
有时\e
并\x1b
不会工作。例如,在shshell 中,有时两者都不起作用(尽管它现在在我的系统上起作用,但我认为以前不会)。
To circumvent this, you can use CTRL+V,CTRL+[or CTRLV,ESC
为了避免这种情况,您可以使用CTRL+ V、CTRL+[或CTRLV,ESC
This will insert a "raw" ESCcharacter (ASCII: 27). It will look like this ^[
, but do not fret; it is only one character—not two.
这将插入一个“原始”ESC字符(ASCII:27)。它看起来像这样^[
,但不要担心;它只有一个字符——而不是两个。
Eg:
例如:
Curses
诅咒
Refer to the Curses (Programming Library) pagefor a full reference on curses. It should be noted that curses only works on unix and unix-like operating systems.
请参阅Curses(编程库)页面以获取有关Curses的完整参考。需要注意的是,curses 仅适用于 unix 和类 Unix 操作系统。
Up and Running with Curses
启动并运行 Curses
I won't go into too much detail, for search engines can reveal links to websites that can explain this much better than I can, but I'll discuss it briefly here and give an example.
我不会详细介绍,因为搜索引擎可以显示比我更能解释这一点的网站链接,但我将在此处简要讨论并举一个例子。
Why Use Curses Over ANSI Escapes?
为什么在 ANSI 转义上使用诅咒?
If you read the above text, you might recall that \e
or \x1b
will sometimes work with printf
. Well, sometimes \e
and \x1b
will not work at all (this is not standard and I have never worked with a terminal like this, but it is possible). More importantly, more complex escape sequences (think Homeand other multi-character keys) are difficult to support for every terminal (unless you are willing to spend a lot of time and effort parsing terminfo and termcap and and figuring out how to handle every terminal).
如果您阅读了上述文本,您可能会记得\e
或\x1b
有时会使用printf
. 嗯,有时候\e
并\x1b
不会在所有的工作(这是不标准,我从来没有与一个终端像这样的工作,但它是可能的)。更重要的Home是,每个终端都难以支持更复杂的转义序列(思考和其他多字符键)(除非您愿意花费大量时间和精力解析 terminfo 和 termcap 并弄清楚如何处理每个终端) .
Curses solves this problem. Basically, it is able to understand what capabilities a terminal has, using these methods (as described by the wikipedia article linked above):
诅咒解决了这个问题。基本上,它能够使用这些方法(如上面链接的维基百科文章所述)了解终端具有哪些功能:
Most implementations of curses use a database that can describe the capabilities of thousands of different terminals. There are a few implementations, such as PDCurses, which use specialized device drivers rather than a terminal database. Most implementations use terminfo; some use termcap. Curses has the advantage of back-portability to character-cell terminals and simplicity. For an application that does not require bit-mapped graphics or multiple fonts, an interface implementation using curses will usually be much simpler and faster than one using an X toolkit.
大多数curses 实现都使用一个可以描述数千个不同终端功能的数据库。有一些实现,例如 PDCurses,它们使用专门的设备驱动程序而不是终端数据库。大多数实现使用 terminfo;有些使用 termcap。Curses 具有向后移植到字符单元终端和简单性的优点。对于不需要位图图形或多种字体的应用程序,使用curses 的接口实现通常比使用X 工具包的接口实现简单和快速得多。
Most of the time, curses will poll terminfo and will then be able to understand how to manipulate the cursor and text attributes. Then, you, the programmer, use the API provided by curses to manipulate the cursor or change the text color or other attributes if the functionality you seek is desired.
大多数时候,curses 会轮询 terminfo,然后将能够理解如何操作光标和文本属性。然后,您,程序员,如果需要您寻求的功能,可以使用curses 提供的API 来操作光标或更改文本颜色或其他属性。
Example with Python
使用 Python 的示例
I find python is really easy to use, but if you want to use curses in a different programming language, then simply search it on duckduckgo or any other search engine. :) Here is a quick example in python 3:
我发现python真的很容易使用,但如果你想在不同的编程语言中使用curses,那么只需在duckduckgo或任何其他搜索引擎上搜索它。:) 这是python 3中的一个快速示例:
import curses
def main(stdscr):
# allow curses to use default foreground/background (39/49)
curses.use_default_colors()
# Clear screen
stdscr.clear()
curses.init_pair(1, curses.COLOR_RED, -1)
curses.init_pair(2, curses.COLOR_GREEN, -1)
stdscr.addstr("ERROR: I like tacos, but I don't have any.\n", curses.color_pair(1))
stdscr.addstr("SUCCESS: I found some tacos.\n", curses.color_pair(2))
stdscr.refresh() # make sure screen is refreshed
stdscr.getkey() # wait for user to press key
if __name__ == '__main__':
curses.wrapper(main)
result:
结果:
You might think to yourself that this is a much more round-about way of doing things, but it really is much more cross-platform (really cross-terminal … at least in the unix- and unix-like-platform world). For colors, it is not quiteas important, but when it comes to supporting other multi-sequence escape sequences (such as Home, End, Page Up, Page Down, etc), then curses becomes all the more important.
您可能会认为这是一种更迂回的做事方式,但它确实更跨平台(真正跨终端……至少在 unix 和 unix 类平台世界中)。对于颜色,这不是很重要,但是当涉及到支持其他多序列转义序列(如Home,End,Page Up,Page Down,等等),然后诅咒变得更加重要。
Example with Tput
使用 Tput 的示例
tput
is a command line utility for manipulating cursor and texttput
comes with thecurses
package. If you want to use cross-terminal (ish) applications in the terminal, you should use tput, as it parses terminfo or whatever it needs to and uses a set of standardized commands (like curses) and returns the correct escape sequence.- example:
tput
是用于操作光标和文本的命令行实用程序tput
随curses
包提供。如果您想在终端中使用跨终端 (ish) 应用程序,您应该使用 tput,因为它会解析 terminfo 或它需要的任何内容,并使用一组标准化命令(如 curses)并返回正确的转义序列。- 例子:
echo "$(tput setaf 1)$(tput bold)ERROR:$(tput sgr0)$(tput setaf 1) My tacos have gone missing"
echo "$(tput setaf 2)$(tput bold)SUCCESS:$(tput sgr0)$(tput setaf 2) Oh good\! I found my tacos\!"
Result:
结果:
More Info on Tput
有关 Tput 的更多信息
- see: http://linuxcommand.org/lc3_adv_tput.phpto see how tput works
- see: http://invisible-island.net/ncurses/man/terminfo.5.htmlfor a list of commands that you can use
- 请参阅:http: //linuxcommand.org/lc3_adv_tput.php以了解 tput 的工作原理
- 请参阅:http: //invisible-island.net/ncurses/man/terminfo.5.html以获取您可以使用的命令列表
回答by DanP
This has worked for me:
这对我有用:
System.out.println((char)27 + "[31mThis text would show up red" + (char)27 + "[0m");
You need the ending "[37m" to return the color to white (or whatever you were using). If you don't it may make everything that follows "red".
您需要结尾“[37m”将颜色恢复为白色(或您使用的任何颜色)。如果你不这样做,它可能会使所有跟随“红色”的东西。
回答by joe
This works in eclipse just to turn it red, don't know about other places.
这在 eclipse 中只是为了把它变成红色,不知道其他地方。
System.err.println(" BLABLA ");