亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將彩色文本輸出到Linux終端?

如何將彩色文本輸出到Linux終端?

富國滬深 2019-08-29 08:13:59
如何將彩色文本輸出到Linux終端?如何將彩色字符打印到支持它的Linux終端?如何判斷終端是否支持顏色代碼?
查看完整描述

3 回答

?
湖上湖

TA貢獻2003條經驗 獲得超2個贊

基本

我編寫了一個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;

}

資源

#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";

        }

    };

}

高級

您可能希望為該類添加其他功能。例如,可以添加顏色洋紅色甚至粗體樣式。為此,只需Code枚舉的另一個條目。這是一個很好的參考。

查看完整回答
反對 回復 2019-08-29
?
慕萊塢森

TA貢獻1810條經驗 獲得超4個贊

在您輸出任何顏色之前,您需要確保您在終端:

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

然后,如果支持顏色,則需要檢查終端功能

在具有terminfo (基于Linux)的系統上,您可以獲得支持的顏色數量

Number_Of_colors_Supported=$(tput colors)

在具有termcap (基于BSD)的系統上,您可以獲得支持的顏色數量

Number_Of_colors_Supported=$(tput Co)

然后讓你決定:

[ ${Number_Of_colors_Supported} -ge 8 ] && {
    echo 'You are fine and can print colors'} || {
    echo 'Terminal does not support color'}

順便說一下,不要像以前用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)"

基于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)"

用于

echo -e "${fg_red}  Red  ${fg_green} Bull ${reset}"


查看完整回答
反對 回復 2019-08-29
  • 3 回答
  • 0 關注
  • 659 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號