手机浏览 RSS 2.0 订阅 膘叔的简单人生 , 腾讯云RDS购买 | 超便宜的Vultr , 注册 | 登陆
浏览模式: 标准 | 列表Tag:phpfog

如何在终端输出带颜色的字体?

终端显示颜色,在以前的想法当中,都是因为有了.profile的配色方案。而我一般也都是 采用默认的(snakevil是写过一个bash带颜色的方案的。我觉得太花哨了就没有使用)

为什么突然间又想到这个?是因为在使用PHP输出LOG的时候,千篇一率,从屏幕中找关键字很累,所以就想着,是不是用PHP也可以输出这种带颜色的关键字?当然,这是因为我正好看到了一个PHP是这么输出的,它就是laraval,它的工具(laraval.phar)在命令行的输出就是有不同颜色的,它给了我指引,意思就是,这个想法是可以实现的。

OK。找资料,知道在终端中用指定的字符来做为背景色和字体色(http://blog.csdn.net/acmee/article/details/6613060)

文中这样介绍:

XML/HTML代码
  1. 一、shell下的实现方法  
  2.   
  3.        先来讲在shell下,如何实现。用echo命令就可以实现,参看以下例子:  
  4.   
  5.        echo  -e  "\033[32mHello, world!"  
  6.   
  7.        当你在终端里敲下这条命令后,是不是发现系统用绿色输出了"Hello,world!",不止如此,连之后的命令提示符都变成了绿色?不要着急,听我继续说。echo命令-e选项的作用是激活终端对反斜线转义符(即\)的解释。引号内\033用于引导非常规字符序列,在这里的作用就是引导设置输出属性,后边的[32m就是将前景色设置为绿色,字母m表示设置的属性类别,数字代表属性值。设置可以单独使用,例如:  
  8.   
  9.        echo -e  "\033[0m"  
  10.   
  11.        这行命令的作用是恢复属性为默认值,也就是说0m设置项用于恢复默认值。现在你的终端是不是又一切正常了?  
  12.   
  13.        理解了这些,剩下的就简单了。用这种命令,除了设置文本前景色,还可以设置很多属性。下边列出其他的设置项:  
  14.   
  15.       --------------------------------------------------------------------------  
  16.   
  17.       \033[0m 关闭所有属性  
  18.       \033[1m 设置高亮度  
  19.       \033[4m 下划线  
  20.       \033[5m 闪烁  
  21.       \033[7m 反显  
  22.       \033[8m 消隐  
  23.       \033[30m 至 \33[37m 设置前景色  
  24.       \033[40m 至 \33[47m 设置背景色  
  25.       \033[nA 光标上移n行   
  26.       \033[nB 光标下移n行  
  27.       \033[nC 光标右移n行  
  28.       \033[nD 光标左移n行  
  29.       \033[y;xH设置光标位置  
  30.       \033[2J 清屏  
  31.       \033[K 清除从光标到行尾的内容  
  32.       \033[s 保存光标位置   
  33.       \033[u 恢复光标位置  
  34.       \033[?25l 隐藏光标  
  35.       \033[?25h 显示光标  
  36.   
  37.       --------------------------------------------------------------------------  
  38.   
  39.       各数字所代表的颜色如下:  
  40.   
  41.       字背景颜色范围:40----49  
  42.       40:黑  
  43.       41:深红  
  44.       42:绿  
  45.       43:黄色  
  46.       44:蓝色  
  47.       45:紫色  
  48.       46:深绿  
  49.       47:白色  
  50.   
  51.       字颜色:30-----------39  
  52.       30:黑  
  53.       31:红  
  54.       32:绿  
  55.       33:黄  
  56.       34:蓝色  
  57.       35:紫色  
  58.       36:深绿   
  59.       37:白色  
  60.   
  61.       另外,同类的多种设置项可以组合在一起,中间用分号(;)隔开。如下:  
  62.   
  63.       echo -e "\033[20;1H\033[1;4;32mHello,world\033[0m"  
  64.   
  65.       这行命令首先\033[20;1H将光标移动到终端第20行第1列,之后的\033[1;4;32m将文本属性设置为高亮、带下划线且颜色为绿色,然后输出Hello,world;最后\033[0m将终端属性恢复为默认值,这样就不会看到连命令完成后的命令提示符也变了样儿了。  
  66.   
  67.       通过以上各种命令的组合就可以实现对终端输出地复杂控制。  
  68.   
  69. 二、如何在C编程中实现?  
  70.   
  71.       理解了以上在Shell中的实现方法,关于在C中如何实现就很简单了。可以说只需要用printf函数代替上边的echo -e就OK了。参见下例:  
  72.   
  73.       int color = 32;  
  74.   
  75.       printf("\033[20;1H\033[1;4;%dmHello, world.\033[0m", color);  
  76.   
  77.       这个例子类似上边shell中最后那个例子,只是这里颜色值通过变量color来指定(当然,也可以直接指定)。  
  78.   
  79. 三、联想  
  80.   
  81.       看到这里你可能会想,是不是在其他编程语言里也可以用类似的方法实现对终端输出的控制呢?答案是肯定的!比如在python中,可以如下输出:  
  82.   
  83.       color=32  
  84.   
  85.       print “\033[20;1H\033[1;4;%dHello, world.\033[0m"%color  
  86.   
  87.       这个例子的效果跟上边C的例子是相同的。  

其实在看到这一段之前,snakevil在自己的github的项目(https://github.com/snakevil/bashrc.x)中也介绍过,其实我相对还是喜欢ubuntu的默认配色,snakevil的这个配色我是真心不是特别喜欢。。

但究竟怎么用PHP输出呢?在用PHP输出之前,找了一下网络,发现已经有有用perl实现过了。那么说实在的。如果没有使用到一些特别的函数,其实php和perl实在是太象了,所以,可以直接参考(http://perldoc.perl.org/Term/ANSIColor.html),这里的代码,除了那个类外,都还是可以复刻的。于是,再随便找了点,果然还是有现成的PHP代码的(http://www.if-not-true-then-false.com/2010/php-class-for-coloring-php-command-line-cli-scripts-output-php-output-colorizing-using-bash-shell-colors/)

好吧。这个URL太长了。还是直接贴代码吧:

PHP代码
  1. <?php  
  2.    
  3.     class Colors {  
  4.         private $foreground_colors = array();  
  5.         private $background_colors = array();  
  6.    
  7.         public function __construct() {  
  8.             // Set up shell colors  
  9.             $this->foreground_colors['black'] = '0;30';  
  10.             $this->foreground_colors['dark_gray'] = '1;30';  
  11.             $this->foreground_colors['blue'] = '0;34';  
  12.             $this->foreground_colors['light_blue'] = '1;34';  
  13.             $this->foreground_colors['green'] = '0;32';  
  14.             $this->foreground_colors['light_green'] = '1;32';  
  15.             $this->foreground_colors['cyan'] = '0;36';  
  16.             $this->foreground_colors['light_cyan'] = '1;36';  
  17.             $this->foreground_colors['red'] = '0;31';  
  18.             $this->foreground_colors['light_red'] = '1;31';  
  19.             $this->foreground_colors['purple'] = '0;35';  
  20.             $this->foreground_colors['light_purple'] = '1;35';  
  21.             $this->foreground_colors['brown'] = '0;33';  
  22.             $this->foreground_colors['yellow'] = '1;33';  
  23.             $this->foreground_colors['light_gray'] = '0;37';  
  24.             $this->foreground_colors['white'] = '1;37';  
  25.    
  26.             $this->background_colors['black'] = '40';  
  27.             $this->background_colors['red'] = '41';  
  28.             $this->background_colors['green'] = '42';  
  29.             $this->background_colors['yellow'] = '43';  
  30.             $this->background_colors['blue'] = '44';  
  31.             $this->background_colors['magenta'] = '45';  
  32.             $this->background_colors['cyan'] = '46';  
  33.             $this->background_colors['light_gray'] = '47';  
  34.         }  
  35.    
  36.         // Returns colored string  
  37.         public function getColoredString($string$foreground_color = null, $background_color = null) {  
  38.             $colored_string = "";  
  39.    
  40.             // Check if given foreground color found  
  41.             if (isset($this->foreground_colors[$foreground_color])) {  
  42.                 $colored_string .= "\033[" . $this->foreground_colors[$foreground_color] . "m";  
  43.             }  
  44.             // Check if given background color found  
  45.             if (isset($this->background_colors[$background_color])) {  
  46.                 $colored_string .= "\033[" . $this->background_colors[$background_color] . "m";  
  47.             }  
  48.    
  49.             // Add string and end coloring  
  50.             $colored_string .=  $string . "\033[0m";  
  51.    
  52.             return $colored_string;  
  53.         }  
  54.    
  55.         // Returns all foreground color names  
  56.         public function getForegroundColors() {  
  57.             return array_keys($this->foreground_colors);  
  58.         }  
  59.    
  60.         // Returns all background color names  
  61.         public function getBackgroundColors() {  
  62.             return array_keys($this->background_colors);  
  63.         }  
  64.     }  
  65.    

用法也比较简单:

PHP代码
  1. <?php  
  2.    
  3.     // Create new Colors class  
  4.     $colors = new Colors();  
  5.    
  6.     // Test some basic printing with Colors class  
  7.     echo $colors->getColoredString("Testing Colors class, this is purple string on yellow background.""purple""yellow") . "\n";  
  8.     echo $colors->getColoredString("Testing Colors class, this is blue string on light gray background.""blue""light_gray") . "\n";  
  9.     echo $colors->getColoredString("Testing Colors class, this is red string on black background.""red""black") . "\n";  
  10.     echo $colors->getColoredString("Testing Colors class, this is cyan string on green background.""cyan""green") . "\n";  
  11.     echo $colors->getColoredString("Testing Colors class, this is cyan string on default background.""cyan") . "\n";  
  12.     echo $colors->getColoredString("Testing Colors class, this is default string on cyan background.", null, "cyan") . "\n";  
  13.    

当然,如果你觉得这个代码太麻烦,还有一个简单的方法:

PHP代码
  1. function colorize($text$status) {  
  2.  $out = "";  
  3.  switch($status) {  
  4.   case "SUCCESS":  
  5.    $out = "[42m"//Green background  
  6.    break;  
  7.   case "FAILURE":  
  8.    $out = "[41m"//Red background  
  9.    break;  
  10.   case "WARNING":  
  11.    $out = "[43m"//Yellow background  
  12.    break;  
  13.   case "NOTE":  
  14.    $out = "[44m"//Blue background  
  15.    break;  
  16.   default:  
  17.    throw new Exception("Invalid status: " . $status);  
  18.  }  
  19.  return chr(27) . "$out" . "$text" . chr(27) . "[0m";  
  20. }  
  21.   
  22. echo colorize("Your command was successfully executed...""SUCCESS");  

四种颜色也够了。不过。。。NOTE的blue background。。。如果你的字符还是黑色的,真心看不到字符串了。

至此,介绍完毕,你可以试试(我已经用在项目中了)

 

 

[转]Developer Time

 其实这篇文章的中文翻译真的好理解,所以我就不翻了啦。懒得翻译的人,可以直接看google translate页面:http://translate.google.com.hk/translate?act=url&hl=en&ie=UTF8&prev=_t&sl=auto&tl=zh-CN&u=http://pydanny.com/developer-time.html

OK,我下面贴的是原文:

This blog post got started with a tweet.

That tweet got retweeted a lot by developers. And system administrators. And database administrators. And any creative type.

As of December 7th, 2012, it had been retweeted over 500 times, a personal best. Obviously I struck a chord that resonated with a lot of people.

Why did this tweet resonate with so many people?

What I said in that tweet was not new - dozens if not hundreds of others have tweeted similar thoughts before and gotten many retweets. Heck, it's been written about in blogs and articles for years, either as a huge rant or often as an effort to politely educate others on how to set up a developer/operations/creative shop.

I think this is because developers/engineers/creatives (and good managers) know that even a tiny distraction to someone "in the zone" takes more than just the 3-5 minutes it takes for you to finish a question and get an answer. Plus, because you are trying to remember the pieces in your head, you won't be able to give this issue your full attention. Which causes a whole other set of issues.

We know this. Good managers know this. Good companies live off of it.

And yet this remains a huge problem for many of us because the distractions keep happening. Maybe it's because your manager doesn't understand this issue, or you have a team mate who can switch in-and-out of the zone with impunity. Or because you foolishly leave the chat/IRC/phone on and you get pinged.

How do we fix it?

We can't.

I know this sounds depressing, but I'm being realistic. Here's some reasons that apply:

  • Unless you are fortunate enough to be working on a solo effort, you are working with other developers/engineers/creatives. And if they can't ask you questions or inform you about critical stuff then you or they can waste hours.
  • Meetings, short or long, online or in person, are a necessary part of any operation. If not with your boss or underlings, then with clients or users.
  • Your boss/co-workers/underlings/kids/pets/parents don't get it that you can't be interrupted.
  • As a freelancer, you can't be inaccessible to existing or potential clients.

No really, how do we fix it?

Doesn't matter how frequently you ask the the question (or rant about it), I don't believe this problem can be really solved. However, here are some possible mitigations:

1. Maker's Day

My friend, Craig Kerstiens describes how Heroku gives engineers a full day each week (Thursday) to focus on getting stuff done. No meetings, no standup, just 100% uninterrupted quiet time to focus on making stuff.

Suggest this at your company and see how it goes!

2. Blocks of Time

As of 2010, Eldarion broke up their work day into at least two sizable chunks of uninterrupted activity. Between the chunks you communicated with co-workers. The advantage of this approach is if you went down the wrong path or someone had a critical question, the period between chunks addressed this issue.

In theory this is how a lot of places work (lunch being the break). The reality is that the distractions often still pile in. For Eldarion it worked because everyone was remote.

3. New Desk Location

If working at an office, asked to be moved to a place with less foot traffic. The downside to this is you can end up in noisy, cold, dark places.

4. New Job

Switch to a new job that promises less distractions.

Maybe I'm wrong

I'm more than happy to be proven wrong.

Maybe there is a way to get 4-6 hours a day of uninterrupted maker's time every work day.

If you've got any ideas, let me know!

-------

没有什么正确的东西,无非就是你自己怎么选择。和你自己是怎么看待被打断的。