Go4Expert (http://www.go4expert.com/)
-   Perl (http://www.go4expert.com/articles/perl-tutorials/)
-   -   Colorize shell output (http://www.go4expert.com/articles/colorize-shell-output-t4079/)

oleber 30Apr2007 14:10

Colorize shell output
Many programs use the STDOUT to produce some normal output and the STDERR to show the errors. I'm actually working with the g++ that do this and a question appeared.

Wouldn't be nice to see it with different colors?

Code: Perl


use strict;
use warnings;

use IPC::Open3;
use IO::Select;
use Term::ANSIColor qw(:constants);


my $pid;
eval { $pid=open3(*WRITE, *READ, *ERROR, @ARGV); };

if (!$pid) {
    # if we get here, the fork succeeded, but the exec (likely) failed...
    my $err = $@ ? $@ : "unknown error";
    # exit child in any case
    die "Error: Could not execute: $err";
} else {
    my $selector=IO::Select->new();
    $selector->add(*READ, *ERROR);
    while(my @ready=$selector->can_read()) {
        foreach my $fh (@ready) {
            my $count = sysread($fh, my $text, 1024);
            $selector->remove($fh) if not $count;

            if(fileno($fh)==fileno(*READ)) {
            } elsif(fileno($fh)==fileno(*ERROR)) {
                print(RED, $text, RESET);

way of use

colorize g++ file.cpp
Useful modules.

use IPC::Open3; : allow to run shell commands and get the STDIN, STDOUT, STDERR.
use IO::Select; : check if a handler has something to be read.
use Term::ANSIColor qw(:constants); : helps to do the colorize.

#anna 10Oct2007 10:59

Re: Colorize shell output
Another Useful modules today. Thanks.

oleber 10Jun2010 10:17

Re: Colorize shell output
Did you like this? look to the new version:


All times are GMT +5.5. The time now is 04:18.