1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

Colorize shell output

Discussion in 'Perl' started by oleber, Apr 30, 2007.

  1. oleber

    oleber New Member

    Joined:
    Apr 23, 2007
    Messages:
    37
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    Software Developer (Perl, C/C++ and Java)
    Location:
    Hamburg, Germany
    Home Page:
    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:
    #!/usr/bin/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 {
        close(*WRITE);
        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)) {
                    print($text); 
                } elsif(fileno($fh)==fileno(*ERROR)) {
                    print(RED, $text, RESET); 
                }
            }
        }
    }
    
    way of use
    Code:
    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.
     
  2. #anna

    #anna New Member

    Joined:
    Oct 10, 2007
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    Another Useful modules today. Thanks.
     
    Last edited by a moderator: Oct 10, 2007
  3. oleber

    oleber New Member

    Joined:
    Apr 23, 2007
    Messages:
    37
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    Software Developer (Perl, C/C++ and Java)
    Location:
    Hamburg, Germany
    Home Page:

Share This Page