macos 如何以跨平台的方式将彩色打印到控制台?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2353430/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 06:47:53  来源:igfitidea点击:

How can I print to the console in color in a cross-platform manner?

linuxmacosconsolecolors

提问by Mike

How can I output colored text using "printf" on both Mac OS X and Linux?

如何在 Mac OS X 和 Linux 上使用“printf”输出彩色文本?

回答by Carl Norum

You can use the ANSI colour codes. Here's an example program:

您可以使用 ANSI 颜色代码。这是一个示例程序:

#include <stdio.h>

int main(int argc, char *argv[])
{
  printf("%c[1;31mHello, world!\n", 27); // red
  printf("%c[1;32mHello, world!\n", 27); // green
  printf("%c[1;33mHello, world!\n", 27); // yellow
  printf("%c[1;34mHello, world!\n", 27); // blue
  return 0;
}

The 27is the escapecharacter. You can use \eif you prefer.

27escape字符。\e如果您愿意,可以使用。

There are lists of all the codes all over the web. Here is one.

网络上有所有代码的列表。 这是一个

回答by lugte098

Another option is:

另一种选择是:

# Define some colors first (you can put this in your .bashrc file):
red='\e[0;31m'
RED='\e[1;31m'
blue='\e[0;34m'
BLUE='\e[1;34m'
cyan='\e[0;36m'
CYAN='\e[1;36m'
green='\e[0;32m'
GREEN='\e[1;32m'
yellow='\e[0;33m'
YELLOW='\e[1;33m'
NC='\e[0m'
#################

Then you can type in the terminal:

然后你可以在终端输入:

echo -e "${RED}This is an error${NC}"
echo -e "${YELLOW}This is a warning${NC}"
echo -e "${GREEN}Everythings fine!${NC}"

Do not forget the ${NC} at the end. NC stands for "no color", which means that after your sentence, it will revert back to normal color. If you forget it, the whole prompt and commands afterwards will be in the color you specified (of course you can type 'echo -e "${NS}"' to change it back).

不要忘记末尾的 ${NC}。NC代表“无色”,意思是说完你的句子后,它会恢复正常的颜色。如果您忘记了它,整个提示和之后的命令将采用您指定的颜色(当然您可以键入 'echo -e "${NS}"' 将其更改回来)。

回答by ephemient

For the best portability, query the terminfodatabase. In shell,

为获得最佳可移植性,请查询terminfo数据库。在外壳中,

colors=(black red green yellow blue magenta cyan white)
for ((i = 0; i < ${#colors[*]}; i++)); do
    ((j=(i+1)%${#colors[*]}))
    printf '%s%s%s on %s%s\n' "$(tput setaf $i)" "$(tput setab $j)" \
            "${colors[i]}" "${colors[j]}" "$(tput op)"
done

will print out

会打印出来

black on red
red on green
green on yellow
yellow on blue
blue on magenta
magenta on cyan
cyan on white
white on black

but in color.

但在颜色上。