Automation: (Was: List of Command Line Tools) - Hijacked from PGP

Al Tobey tobert at gmail.com
Sun May 17 10:51:37 MST 2009


On Sun, May 17, 2009 at 6:39 AM, Bryan O'Neal
<boneal at cornerstonehome.com> wrote:
> Great list. I would also add scp (secure copy) ps aux (list of currently
> running processes) and I also like any app that has a command line function,
> like xmms.
>
> While we are on the subject, excluding writing everything in bash, what is
> the best way for various programs (pick your language) to access command
> line tools and parse the output?  I would like to crank my automation
> techniques up a level.

In perl,

use strict;
use warnings;

# pipe at the end of the open string means run the program and grab its stdout
# pipe at the beginning means let me print to its stdin
# see perldoc -f open
# see perldoc IPC::Open2 for how to do both sides
open( my $fh, '/usr/bin/foo |' )
    or die "Could not execute foo: $!";

while ( my $line = <$fh> ) {
    chomp($line); # kill whatever newline/carriage return may be there
     # process it ...
}

close $fh; # optional, but good style

The old standards are still good too, just not as elegant (most of the time).

my @output = `/usr/bin/foo`;
system( '/usr/bin/foo' );

Also check out http://search.cpan.org/~rcaputo/POE-1.005/lib/POE/Wheel/Run.pm

POE takes a bit to learn, but it's really worth it when you have a
single process managing hundreds of tasks without threading or fork.
Python's twisted framework should have something similar and work
similarly, but would be more likely to appease the language snobs.

-Al


More information about the PLUG-discuss mailing list