PHP Command-Line PHP
Colorizing Console Output
Problem
You want to display console output in different colors.
Solution
Use PEAR’s Console_Color2 class:
$color = new Console_Color2();
$ok = $color->color('green');
$fail = $color->color('red');
$reset = $color->color('reset');
print $ok . "OK " . $reset . "Something succeeded!\n";
print $fail . "FAIL " . $reset . "Something failed!\n";
If you’re already using ncurses, incorporate colors by using the appropriate functions:
ncurses_init();
ncurses_start_color();
ncurses_init_pair(1, NCURSES_COLOR_GREEN, NCURSES_COLOR_BLACK);
ncurses_init_pair(2, NCURSES_COLOR_RED, NCURSES_COLOR_BLACK);
ncurses_init_pair(3, NCURSES_COLOR_WHITE, NCURSES_COLOR_BLACK);
ncurses_color_set(1);
ncurses_addstr("OK ");
ncurses_color_set(3);
ncurses_addstr("Something succeeded!\n");
ncurses_color_set(2);
ncurses_addstr("FAIL ");
ncurses_color_set(3);
ncurses_addstr("Something succeeded!\n");
Discussion
By including special escape sequences in console output, you can instruct the console to display text in different colors. Instead of having to remember the magical numbers of the different special characters that make up these escape sequences, use PEAR’s Console_Color2. Its color() method returns a string containing the right escape sequence to change colors.
When one of those strings is included in the output stream, it changes the color of all subsequent text (until another escape sequence alters the active color). In addition to the special “color” reset (which resets the active color to the default), the color() method understands the following color names: black, red, green, brown, blue, purple, cyan, grey, and yellow.
The ncurses extension also offers its own functions for manipulating color. Although the syntax is different, logically it behaves the same way. Color values are defined, and then function calls (to ncurses_color_set()) that alter the “active” color can be interspersed with functions that output text.
No comments:
Post a Comment