给终端来点彩色(c语言和Golang版)
如果用过AIX或Linux下的nmon工具的应当会注意到,它可以把文字显示成多种颜色,并巧妙的利用颜色和字符组合出各种图形 来显示系统的运行情况。看看它官网附的这张图: 如果你看过它的源码,你会发现它用的是 Ncurses 库来实现彩色显示的。Ncurses很强大,可以在任何遵循ANSI/POSIX标准的UNIX系统上运行, 包含了一系列强大的功能。 但在这里,它并不是我要研究的对象,它太重量级了。 我想在这说明的是一种简单的可以让终端显示彩色文本的方法。利用16进制的颜色控制符就足以在终端打印出各种颜色了。这种方法不必调用 API,使用方式也很简单,我用c语言演示下:
#include <stdio.h> int main(void) { printf("x1b[0;%dmhello world 30: 黑 nx1b[0m",30); printf("x1b[0;%dmhello world 31: 红 nx1b[0m",31); printf("x1b[0;%dmhello world 32: 绿 nx1b[0m",32); printf("x1b[0;%dmhello world 33: 黄 nx1b[0m",33); printf("x1b[0;%dmhello world 34: 蓝 nx1b[0m",34); printf("x1b[0;%dmhello world 35: 紫 nx1b[0m",35); printf("x1b[0;%dmhello world 36: 深绿 nx1b[0m",36); printf("x1b[0;%dmhello world 37: 白色 nx1b[0m",37); printf("x1b[%d;%dmhello world x1b[0m 47: 白色 30: 黑 n",47,30); printf("x1b[%d;%dmhello world x1b[0m 46: 深绿 31: 红 n",46,31); printf("x1b[%d;%dmhello world x1b[0m 45: 紫 32: 绿 n",45,32); printf("x1b[%d;%dmhello world x1b[0m 44: 蓝 33: 黄 n",44,33); printf("x1b[%d;%dmhello world x1b[0m 43: 黄 34: 蓝 n",43,34); printf("x1b[%d;%dmhello world x1b[0m 42: 绿 35: 紫 n",42,35); printf("x1b[%d;%dmhello world x1b[0m 41: 红 36: 深绿 n",41,36); printf("x1b[%d;%dmhello world x1b[0m 40: 黑 37: 白色 n",40,37); }可以看到上面只有一个printf函数加一些奇怪的字符,但看看运行效果:
可以看到,传入合适的数字,可以控制文本的颜色及背景颜色,不过有个限制,只能显示上面列出的几种颜色。其中文字颜色编码 从30至37,背景色编码从40至47. 知道这个技巧后,很容易就可以用 Golang封装了,因为它本质只是个打印而已。我封装了一个放在Github上。 网址是:https://github.com/xcltapestry/xclpkg/tree/master/clcolor Golang的调用例子:
package main import ( "fmt" "github.com/xclpkg/clcolor" ) func main() { fmt.Println(clcolor.Black("Black()")) fmt.Println(clcolor.Red("Red()")) fmt.Println(clcolor.Green("Green()")) fmt.Println(clcolor.Yellow("Yellow()")) fmt.Println(clcolor.Blue("Blue()")) fmt.Println(clcolor.Magenta("Magenta()")) fmt.Println(clcolor.Cyan("Cyan()")) fmt.Println(clcolor.White("White()")) }运行效果 :
可以用这个包方便的设置其文本显示颜色,可以用在如日志或一些句子强调显示等情况下。 另外要注意的事,用这种方法设置的彩色显示,如果你是用CRT或SSH等终端来登录查看的,记得 "Enable ANSI color",不然会没效果。 既然UNIX/Linux有这种方式可以在终端显示颜色,那Windows可不可以也用这种方式呢? 其实是有的:
同时也有提供相应的API函数: HANDLE GetStdHandle(DWORD nStdHandle); 传入STD_OUTPUT_HANDLE就可以得到控制台输出设备的句柄。 可以看到,Windows用上面这两个函数即可办到。 不过我比较少在Windows控制台中去看日志,在这就不在做说明和封装了。
MAIL: xcl_168@aliyun.com BLOG: http://blog.csdn.net/xcl168 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |