如何将彩色文本输出到Linux终端?

Mac*_*cha 281 c++ linux terminal colors

如何将彩色字符打印到支持它的Linux终端?

如何判断终端是否支持颜色代码?

Tho*_*mas 376

您需要输出ANSI颜色代码.请注意,并非所有终端都支持此功能 如果不支持颜色序列,则会显示垃圾.

例:

 cout << "\033[1;31mbold red text\033[0m\n";
Run Code Online (Sandbox Code Playgroud)

这里\033是ESC字符,ASCII 27.接下来是[零个或多个数字;,最后是字母m.这些数字描述了从那一点开始切换到的颜色和格式.

前景色和背景色的代码是:

         foreground background
black        30         40
red          31         41
green        32         42
yellow       33         43
blue         34         44
magenta      35         45
cyan         36         46
white        37         47
Run Code Online (Sandbox Code Playgroud)

此外,您可以使用以下内容:

reset             0  (everything back to normal)
bold/bright       1  (often a brighter shade of the same colour)
underline         4
inverse           7  (swap foreground and background colours)
bold/bright off  21
underline off    24
inverse off      27
Run Code Online (Sandbox Code Playgroud)

有关其他广泛支持的代码,请参阅维基百科上表格.


要确定终端是否支持颜色序列,请读取TERM环境变量的值.应该指定使用的特定终端类型(例如vt100,gnome-terminal,xterm,screen,...).然后在terminfo数据库中查找; 检查colors能力.

  • 我使用它来定义"操纵器",例如`const std :: string red("\ 033 [0; 31m");`或`const std :: string reset("\ 033 [0m");`.然后,我可以简单地写出`cout << red <<"red text"<< reset << endl;`. (18认同)
  • 这是蜜蜂在BBS上的膝盖...... (14认同)
  • `m`做什么/代表什么? (10认同)
  • @nipponese`\033 [`和`m`标记ANSI颜色代码的转义序列的开头和结尾.参考:http://en.wikipedia.org/wiki/ANSI_escape_code#CSI_codes (4认同)
  • 我会看一下这种颜色的可视化效果:http://misc.flogisoft.com/bash/tip_colors_and_formatting (2认同)

Joe*_*ren 91

基本

我编写了一个C++类,可用于设置输出的前景色和背景色.此示例程序用作打印This ->word<- is red.和格式化它的示例,以使前景色word为红色.

#include "colormod.h" // namespace Color
#include <iostream>
using namespace std;
int main() {
    Color::Modifier red(Color::FG_RED);
    Color::Modifier def(Color::FG_DEFAULT);
    cout << "This ->" << red << "word" << def << "<- is red." << endl;
}
Run Code Online (Sandbox Code Playgroud)

资源

#include <ostream>
namespace Color {
    enum Code {
        FG_RED      = 31,
        FG_GREEN    = 32,
        FG_BLUE     = 34,
        FG_DEFAULT  = 39,
        BG_RED      = 41,
        BG_GREEN    = 42,
        BG_BLUE     = 44,
        BG_DEFAULT  = 49
    };
    class Modifier {
        Code code;
    public:
        Modifier(Code pCode) : code(pCode) {}
        friend std::ostream&
        operator<<(std::ostream& os, const Modifier& mod) {
            return os << "\033[" << mod.code << "m";
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

高级

您可能希望为该类添加其他功能.例如,可以添加颜色洋红色甚至粗体样式.为此,只需Code枚举的另一个条目.是一个很好的参考.

  • 更多:`FG_DEFAULT = 39,FG_BLACK = 30,FG_RED = 31,FG_GREEN = 32,FG_YELLOW = 33,FG_BLUE = 34,FG_MAGENTA = 35,FG_CYAN = 36,FG_LIGHT_GRAY = 37,FG_DARK_GRAY = 90,FG_LIGHT_RED = 91,FG_LIGHT_GREEN = 92,FG_LIGHT_YELLOW = 93,FG_LIGHT_BLUE = 94,FG_LIGHT_MAGENTA = 95,FG_LIGHT_CYAN = 96,FG_WHITE = 97,BG_RED = 41,BG_GREEN = 42,BG_BLUE = 44,BG_DEFAULT = 49 (7认同)
  • 如果为`Code`定义`operator <<`,那么你可以直接编写`std :: cout << Color :: FG_RED;`而不是`std :: cout << Modifier(Color :: FG_RED);`.也就是说,不需要`修饰符`. (6认同)
  • @Nawaz好主意.这是一个类似的实现:http://pastebin.com/zWC3t9hC.但是我会将我原来的实现保留在答案中,因为我觉得它更具可扩展性. (2认同)

Ale*_*lex 41

在您输出任何颜色之前,您需要确保您在终端:

[ -t 1 ] && echo 'Yes I am in a terminal'  # isatty(3) call in C
Run Code Online (Sandbox Code Playgroud)

然后,如果支持颜色,则需要检查终端功能

在具有terminfo (基于Linux)的系统上,您可以获得支持的颜色数量

Number_Of_colors_Supported=$(tput colors)
Run Code Online (Sandbox Code Playgroud)

在具有termcap (基于BSD)的系统上,您可以获得支持的颜色数量

Number_Of_colors_Supported=$(tput Co)
Run Code Online (Sandbox Code Playgroud)

然后让你决定:

[ ${Number_Of_colors_Supported} -ge 8 ] && {
    echo 'You are fine and can print colors'
} || {
    echo 'Terminal does not support color'
}
Run Code Online (Sandbox Code Playgroud)

顺便说一下,不要像以前用ESC字符那样使用着色.使用标准调用终端功能,为您分配特定终端支持的CORRECT颜色.

基于BSD
fg_black="$(tput AF 0)"
fg_red="$(tput AF 1)"
fg_green="$(tput AF 2)"
fg_yellow="$(tput AF 3)"
fg_blue="$(tput AF 4)"
fg_magenta="$(tput AF 5)"
fg_cyan="$(tput AF 6)"
fg_white="$(tput AF 7)"
reset="$(tput me)"
Run Code Online (Sandbox Code Playgroud) 基于Linux
fg_black="$(tput setaf 0)"
fg_red="$(tput setaf 1)"
fg_green="$(tput setaf 2)"
fg_yellow="$(tput setaf 3)"
fg_blue="$(tput setaf 4)"
fg_magenta="$(tput setaf 5)"
fg_cyan="$(tput setaf 6)"
fg_white="$(tput setaf 7)"
reset="$(tput sgr0)"
Run Code Online (Sandbox Code Playgroud) 用于
echo -e "${fg_red}  Red  ${fg_green} Bull ${reset}"
Run Code Online (Sandbox Code Playgroud)

  • 这个bash不具体吗?-t 1显然不能在C++中工作,调用这个tput程序会使它在C++程序中变得非常迂回. (3认同)
  • @Macha,是的,``[ - t 1]`它是特定的sh/bash,但是在#(注释)符号之后的右侧有C函数做同样的事情.`man 3 isatty`应该对此有所帮助;)示例显示为shell命令以简化主要点的解释.关于`tput`,它是用于查询标准终端能力接口的OPEN源实用程序. (2认同)

gon*_*332 34

正如其他人所说,你可以使用转义字符.您可以使用我的标题以使其更容易:

#ifndef _COLORS_
#define _COLORS_

/* FOREGROUND */
#define RST  "\x1B[0m"
#define KRED  "\x1B[31m"
#define KGRN  "\x1B[32m"
#define KYEL  "\x1B[33m"
#define KBLU  "\x1B[34m"
#define KMAG  "\x1B[35m"
#define KCYN  "\x1B[36m"
#define KWHT  "\x1B[37m"

#define FRED(x) KRED x RST
#define FGRN(x) KGRN x RST
#define FYEL(x) KYEL x RST
#define FBLU(x) KBLU x RST
#define FMAG(x) KMAG x RST
#define FCYN(x) KCYN x RST
#define FWHT(x) KWHT x RST

#define BOLD(x) "\x1B[1m" x RST
#define UNDL(x) "\x1B[4m" x RST

#endif  /* _COLORS_ */
Run Code Online (Sandbox Code Playgroud)

使用标头宏的示例可以是:

#include <iostream>
#include "colors.h"
using namespace std;

int main()
{
    cout << FBLU("I'm blue.") << endl;
    cout << BOLD(FBLU("I'm blue-bold.")) << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Dan*_*ica 15

我使用以下解决方案,它非常简单和优雅,可以轻松粘贴到源代码中,并且适用于Linux/Bash:

const std::string red("\033[0;31m");
const std::string green("\033[1;32m");
const std::string yellow("\033[1;33m");
const std::string cyan("\033[0;36m");
const std::string magenta("\033[0;35m");
const std::string reset("\033[0m");

std::cout << "Measured runtime: " << yellow << timer.count() << reset << std::endl;
Run Code Online (Sandbox Code Playgroud)


Fen*_*ang 13

根据我的理解,典型的ANSI颜色代码

"\033[{FORMAT_ATTRIBUTE};{FORGROUND_COLOR};{BACKGROUND_COLOR}m{TEXT}\033[{RESET_FORMATE_ATTRIBUTE}m"
Run Code Online (Sandbox Code Playgroud)

由(名称和编解码器)组成

  • 格式属性

    { "Default", "0" },
    { "Bold", "1" },
    { "Dim", "2" },
    { "Underlined", "3" },
    { "Blink", "5" },
    { "Reverse", "7" },
    { "Hidden", "8" }
    
    Run Code Online (Sandbox Code Playgroud)
  • 地下颜色

    { "Default", "39" },
    { "Black", "30" },
    { "Red", "31" },
    { "Green", "32" },
    { "Yellow", "33" },
    { "Blue", "34" },
    { "Magenta", "35" },
    { "Cyan", "36" },
    { "Light Gray", "37" },
    { "Dark Gray", "90" },
    { "Light Red", "91" },
    { "Light Green", "92" },
    { "Light Yellow", "93" },
    { "Light Blue", "94" },
    { "Light Magenta", "95" },
    { "Light Cyan", "96" },
    { "White", "97" }
    
    Run Code Online (Sandbox Code Playgroud)
  • 背景颜色

    { "Default", "49" },
    { "Black", "40" },
    { "Red", "41" },
    { "Green", "42" },
    { "Yellow", "43" },
    { "Blue", "44" },
    { "Megenta", "45" },
    { "Cyan", "46" },
    { "Light Gray", "47" },
    { "Dark Gray", "100" },
    { "Light Red", "101" },
    { "Light Green", "102" },
    { "Light Yellow", "103" },
    { "Light Blue", "104" },
    { "Light Magenta", "105" },
    { "Light Cyan", "106" },
    { "White", "107" }
    
    Run Code Online (Sandbox Code Playgroud)
  • 文本

  • 重置格式属性

    { "All", "0" },
    { "Bold", "21" },
    { "Dim", "22" },
    { "Underlined", "24" },
    { "Blink", "25" },
    { "Reverse", "27" },
    { "Hidden", "28" }
    
    Run Code Online (Sandbox Code Playgroud)

有了这些信息,就可以轻松地将字符串着色为"我是香蕉!" 背景颜色为"黄色",背景颜色为"绿色",如下所示

"\033[0;33;42mI am a Banana!\033[0m"
Run Code Online (Sandbox Code Playgroud)

或者用C++库着色

auto const& colorized_text = color::rize( "I am a banana!", "Yellow", "Green" );
std::cout << colorized_text << std::endl;
Run Code Online (Sandbox Code Playgroud)

这里有FORMAT ATTRIBUTE的更多示例在此输入图像描述

  • 好吧,我明白了,你是香蕉! (3认同)

Chr*_*ras 12

这是一个古老的主题,但我编写了一个带有嵌套子类和静态成员的类,用于由简单的C宏定义的颜色.

我通过用户no2pencil从dreamincode.net中的color这篇文章中编写Color Text In C Programming中的函数.

我这样做是为了能够在std :: cout流中使用静态常量,如下所示:

cout << zkr::cc::fore::red << "This is red text. " 
     << zkr::cc::console << "And changing to console default colors, fg, bg."
     << endl;
Run Code Online (Sandbox Code Playgroud)

该类和测试程序源代码可以在这里下载.

cc::console将重置为控制台的默认颜色和属性,cc::underline将下划线文本,该文本适用于我测试过测试程序的putty.

颜色:

black
blue
red
magenta
green
cyan
yellow
white

lightblack
lightblue
lightred
lightmagenta
lightgreen
lightcyan
lightyellow
lightwhite
Run Code Online (Sandbox Code Playgroud)

哪个可以foreback静态类的静态子类和静态子cc类一起使用.

编辑2017

我只是在这里添加类代码以更实用.

颜色代码宏:

#define CC_CONSOLE_COLOR_DEFAULT "\033[0m"
#define CC_FORECOLOR(C) "\033[" #C "m"
#define CC_BACKCOLOR(C) "\033[" #C "m"
#define CC_ATTR(A) "\033[" #A "m"
Run Code Online (Sandbox Code Playgroud)

以及为屏幕定义颜色或属性的主要颜色功能:

char *cc::color(int attr, int fg, int bg)
{
    static char command[13];

    /* Command is the control command to the terminal */
    sprintf(command, "%c[%d;%d;%dm", 0x1B, attr, fg + 30, bg + 40);
    return command;
}
Run Code Online (Sandbox Code Playgroud)

ccolor.h

#include <stdio.h>

#define CC_CONSOLE_COLOR_DEFAULT "\033[0m"
#define CC_FORECOLOR(C) "\033[" #C "m"
#define CC_BACKCOLOR(C) "\033[" #C "m"
#define CC_ATTR(A) "\033[" #A "m"

namespace zkr
{
    class cc
    {
    public:

        class fore
        {
        public:
            static const char *black;
            static const char *blue;
            static const char *red;
            static const char *magenta;
            static const char *green;
            static const char *cyan;
            static const char *yellow;
            static const char *white;
            static const char *console;

            static const char *lightblack;
            static const char *lightblue;
            static const char *lightred;
            static const char *lightmagenta;
            static const char *lightgreen;
            static const char *lightcyan;
            static const char *lightyellow;
            static const char *lightwhite;
        };

        class back
        {
        public:
            static const char *black;
            static const char *blue;
            static const char *red;
            static const char *magenta;
            static const char *green;
            static const char *cyan;
            static const char *yellow;
            static const char *white;
            static const char *console;

            static const char *lightblack;
            static const char *lightblue;
            static const char *lightred;
            static const char *lightmagenta;
            static const char *lightgreen;
            static const char *lightcyan;
            static const char *lightyellow;
            static const char *lightwhite;
        };

        static char *color(int attr, int fg, int bg);
        static const char *console;
        static const char *underline;
        static const char *bold;
    };
}
Run Code Online (Sandbox Code Playgroud)

ccolor.cpp

#include "ccolor.h"

using namespace std;

namespace zkr
{
    enum Color
    {
        Black,
        Red,
        Green,
        Yellow,
        Blue,
        Magenta,
        Cyan,
        White,
        Default = 9
    };

    enum Attributes
    {
        Reset,
        Bright,
        Dim,
        Underline,
        Blink,
        Reverse,
        Hidden
    };

    char *cc::color(int attr, int fg, int bg)
    {
        static char command[13];
        /* Command is the control command to the terminal */
        sprintf(command, "%c[%d;%d;%dm", 0x1B, attr, fg + 30, bg + 40);
        return command;
    }

    const char *cc::console = CC_CONSOLE_COLOR_DEFAULT;
    const char *cc::underline = CC_ATTR(4);
    const char *cc::bold = CC_ATTR(1);

    const char *cc::fore::black = CC_FORECOLOR(30);
    const char *cc::fore::blue = CC_FORECOLOR(34);
    const char *cc::fore::red = CC_FORECOLOR(31);
    const char *cc::fore::magenta = CC_FORECOLOR(35);
    const char *cc::fore::green = CC_FORECOLOR(92);
    const char *cc::fore::cyan = CC_FORECOLOR(36);
    const char *cc::fore::yellow = CC_FORECOLOR(33);
    const char *cc::fore::white = CC_FORECOLOR(37);
    const char *cc::fore::console = CC_FORECOLOR(39);

    const char *cc::fore::lightblack = CC_FORECOLOR(90);
    const char *cc::fore::lightblue = CC_FORECOLOR(94);
    const char *cc::fore::lightred = CC_FORECOLOR(91);
    const char *cc::fore::lightmagenta = CC_FORECOLOR(95);
    const char *cc::fore::lightgreen = CC_FORECOLOR(92);
    const char *cc::fore::lightcyan = CC_FORECOLOR(96);
    const char *cc::fore::lightyellow = CC_FORECOLOR(93);
    const char *cc::fore::lightwhite = CC_FORECOLOR(97);

    const char *cc::back::black = CC_BACKCOLOR(40);
    const char *cc::back::blue = CC_BACKCOLOR(44);
    const char *cc::back::red = CC_BACKCOLOR(41);
    const char *cc::back::magenta = CC_BACKCOLOR(45);
    const char *cc::back::green = CC_BACKCOLOR(42);
    const char *cc::back::cyan = CC_BACKCOLOR(46);
    const char *cc::back::yellow = CC_BACKCOLOR(43);
    const char *cc::back::white = CC_BACKCOLOR(47);
    const char *cc::back::console = CC_BACKCOLOR(49);

    const char *cc::back::lightblack = CC_BACKCOLOR(100);
    const char *cc::back::lightblue = CC_BACKCOLOR(104);
    const char *cc::back::lightred = CC_BACKCOLOR(101);
    const char *cc::back::lightmagenta = CC_BACKCOLOR(105);
    const char *cc::back::lightgreen = CC_BACKCOLOR(102);
    const char *cc::back::lightcyan = CC_BACKCOLOR(106);
    const char *cc::back::lightyellow = CC_BACKCOLOR(103);
    const char *cc::back::lightwhite = CC_BACKCOLOR(107);
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你的代码.我添加了另一个[ANSI转义码](http://en.wikipedia.org/wiki/ANSI_escape_code#Colors)以允许显示粗体文本:`const char*cc :: bold = CC_ATTR(1);` (2认同)

Vla*_*lad 9

如果您的终端支持,您可以使用转义序列.例如:

echo \[\033[32m\]Hello, \[\033[36m\]colourful \[\033[33mworld!\033[0m\]
Run Code Online (Sandbox Code Playgroud)


Sha*_*des 7

gon1332标头的扩展版本:

//
//  COLORS.h
//
//  Posted by Gon1332 May 15 2015 on StackOverflow
//  /sf/ask/183183451/#2616912
//
//  Description: An easy header file to make colored text output to terminal second nature.
//  Modified by Shades Aug. 14 2018

// PLEASE carefully read comments before using this tool, this will save you a lot of bugs that are going to be just about impossible to find.
#ifndef COLORS_h
#define COLORS_h

/* FOREGROUND */
// These codes set the actual text to the specified color
#define RESETTEXT  "\x1B[0m" // Set all colors back to normal.
#define FOREBLK  "\x1B[30m" // Black
#define FORERED  "\x1B[31m" // Red
#define FOREGRN  "\x1B[32m" // Green
#define FOREYEL  "\x1B[33m" // Yellow
#define FOREBLU  "\x1B[34m" // Blue
#define FOREMAG  "\x1B[35m" // Magenta
#define FORECYN  "\x1B[36m" // Cyan
#define FOREWHT  "\x1B[37m" // White

/* BACKGROUND */
// These codes set the background color behind the text.
#define BACKBLK "\x1B[40m"
#define BACKRED "\x1B[41m"
#define BACKGRN "\x1B[42m"
#define BACKYEL "\x1B[43m"
#define BACKBLU "\x1B[44m"
#define BACKMAG "\x1B[45m"
#define BACKCYN "\x1B[46m"
#define BACKWHT "\x1B[47m"

// These will set the text color and then set it back to normal afterwards.
#define BLK(x) FOREBLK x RESETTEXT
#define RED(x) FORERED x RESETTEXT
#define GRN(x) FOREGRN x RESETTEXT
#define YEL(x) FOREYEL x RESETTEXT
#define BLU(x) FOREBLU x RESETTEXT
#define MAG(x) FOREMAG x RESETTEXT
#define CYN(x) FORECYN x RESETTEXT
#define WHT(x) FOREWHT x RESETTEXT

// Example usage: cout << BLU("This text's color is now blue!") << endl;

// These will set the text's background color then reset it back.
#define BackBLK(x) BACKBLK x RESETTEXT
#define BackRED(x) BACKRED x RESETTEXT
#define BackGRN(x) BACKGRN x RESETTEXT
#define BackYEL(x) BACKYEL x RESETTEXT
#define BackBLU(x) BACKBLU x RESETTEXT
#define BackMAG(x) BACKMAG x RESETTEXT
#define BackCYN(x) BACKCYN x RESETTEXT
#define BackWHT(x) BACKWHT x RESETTEXT

// Example usage: cout << BACKRED(FOREBLU("I am blue text on a red background!")) << endl;

// These functions will set the background to the specified color indefinitely.
// NOTE: These do NOT call RESETTEXT afterwards. Thus, they will set the background color indefinitely until the user executes cout << RESETTEXT
// OR if a function is used that calles RESETTEXT i.e. cout << RED("Hello World!") will reset the background color since it calls RESETTEXT.
// To set text COLOR indefinitely, see SetFore functions below.
#define SetBackBLK BACKBLK
#define SetBackRED BACKRED
#define SetBackGRN BACKGRN
#define SetBackYEL BACKYEL
#define SetBackBLU BACKBLU
#define SetBackMAG BACKMAG
#define SetBackCYN BACKCYN
#define SetBackWHT BACKWHT

// Example usage: cout << SetBackRED << "This text's background and all text after it will be red until RESETTEXT is called in some way" << endl;

// These functions will set the text color until RESETTEXT is called. (See above comments)
#define SetForeBLK FOREBLK
#define SetForeRED FORERED
#define SetForeGRN FOREGRN
#define SetForeYEL FOREYEL
#define SetForeBLU FOREBLU
#define SetForeMAG FOREMAG
#define SetForeCYN FORECYN
#define SetForeWHT FOREWHT

// Example usage: cout << SetForeRED << "This text and all text after it will be red until RESETTEXT is called in some way" << endl;

#define BOLD(x) "\x1B[1m" x RESETTEXT // Embolden text then reset it.
#define BRIGHT(x) "\x1B[1m" x RESETTEXT // Brighten text then reset it. (Same as bold but is available for program clarity)
#define UNDL(x) "\x1B[4m" x RESETTEXT // Underline text then reset it.

// Example usage: cout << BOLD(BLU("I am bold blue text!")) << endl;

// These functions will embolden or underline text indefinitely until RESETTEXT is called in some way.

#define SetBOLD "\x1B[1m" // Embolden text indefinitely.
#define SetBRIGHT "\x1B[1m" // Brighten text indefinitely. (Same as bold but is available for program clarity)
#define SetUNDL "\x1B[4m" // Underline text indefinitely.

// Example usage: cout << setBOLD << "I and all text after me will be BOLD/Bright until RESETTEXT is called in some way!" << endl;

#endif /* COLORS_h */
Run Code Online (Sandbox Code Playgroud)

如您所见,它具有更多功能,例如临时,无限期设置背景颜色的功能以及其他功能。我也相信它对初学者更友好,并且更容易记住所有功能。

#include <iostream>
#include "COLORS.h"

int main() {
  std::cout << SetBackBLU << SetForeRED << endl;
  std::cout << "I am red text on a blue background! :) " << endl;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

只需将头文件包括在您的项目中,即可准备好使用彩色的终端输出来摇摆。