Linux下的多彩终端


=Start=

缘由:

在Linux终端上进行调试的时候,希望能够以不同的颜色对日志进行区分,方便查看。之前有过一定了解,现在希望能够整理一下这方面的知识,记录在blog上方便自己查阅和使用。

正文:
1.如何判断我的终端是否能够输出彩色文字?

你可以通过下面的Bash脚本判断当前终端是否支持各种颜色:

# http://unix.stackexchange.com/a/10065
# check if stdout is a terminal...
if test -t 1; then

    # see if it supports colors...
    ncolors=$(tput colors)

    if test -n "$ncolors" && test $ncolors -ge 8; then
        bold="$(tput bold)"
        underline="$(tput smul)"
        standout="$(tput smso)"
        normal="$(tput sgr0)"
        black="$(tput setaf 0)"
        red="$(tput setaf 1)"
        green="$(tput setaf 2)"
        yellow="$(tput setaf 3)"
        blue="$(tput setaf 4)"
        magenta="$(tput setaf 5)"
        cyan="$(tput setaf 6)"
        white="$(tput setaf 7)"
    fi
fi

echo "${red}error${normal}"
echo "${green}success${normal}"

echo "${green}0.052${normal} ${bold}${green}2,816.00 kb${normal}"
# etc.
2.在Bash脚本中如何输出彩色文字?
#!/bin/bash

BLACK="\033[30m"
RED="\033[31m"
GREEN="\033[32m"
YELLOW="\033[33m"
BLUE="\033[34m"
PINK="\033[35m"
CYAN="\033[36m"
WHITE="\033[37m"
NORMAL="\033[0;39m"

printf "URL: $GREEN http://highon.coffee $NORMAL \n"
sleep 0.4

printf "Version: $YELLOW 1.0 $NORMAL \n"
sleep 0.4

printf "Twitter: $BLUE @HighOn_Coffee $NORMAL \n"
sleep 0.2

printf "Author: $BLUE @Arr0way $NORMAL \n"
sleep 0.4

printf "Disclaimer: \n"
printf "$RED\t HighOn.Coffee is not responsible for misuse or for any damage that you may cause!\n\t You agree that you use this software at your own risk. $NORMAL \n"
sleep 2

printf "\n"
printf "$BLUE"
printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' '#'
printf "## $RED Kernel Info"
printf "\n"
printf "$BLUE"
printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' '#'
printf "\n"
printf "$NORMAL"

printf "$BLUE"
printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' '#'
printf "## $RED Mounted File Systems with Pretty Output"
printf "\n"
printf "$BLUE"
printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' '#'
printf "\n"
printf "$NORMAL"
/bin/df -h

输出效果如下:

bash_color_print

3.在Python程序中如何输出彩色文字?

最通用的办法就是和上面一样——打印ANSI转义序列,比如:

# http://stackoverflow.com/a/287944

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

print bcolors.WARNING + "Warning: No active frommets remain. Continue?" + bcolors.ENDC

其次就是使用一些现成的模块进行打印,但可能存在平台通用性的问题。

参考链接:

=END=


《“Linux下的多彩终端”》 有 1 条评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注