Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??

Updated: November 9, 2016

The following is a cross-platform demonstration for capturing STDERR.

use strict; use warnings; use File::Temp qw/ tempfile /; # Initially, borrowed bits from IPC::Run3 for capturing STDERR. # Then, made efficient for lesser overhead than Capture::Tiny. sub do_cmd { my ( $cmd ) = @_; my ( undef, $err_file ) = tempfile(); my ( $err, $err_fh, @result ) = (''); if ( $^O eq 'MSWin32' ) { # this is one way to capture STDERR, also works on Unix open my $cmd_fh, "$cmd 2> $err_file |" or die "$!\n"; @result = <$cmd_fh> if defined ( fileno $cmd_fh ); close $cmd_fh; } else { # this is another way, but not supported on Windows local *STDERR_SAVE; open STDERR_SAVE, '>&STDERR'; open $err_fh, '+>', $err_file; binmode $err_fh, ':raw'; open STDERR, '>&' . fileno $err_fh; open my $cmd_fh, "$cmd |" or die "$!\n"; @result = <$cmd_fh> if defined ( fileno $cmd_fh ); close $cmd_fh; open STDERR, '>&STDERR_SAVE'; close $err_fh; } if ( -s $err_file ) { open $err_fh, '<', $err_file; local $/ = undef; $err = <$err_fh>; close $err_fh; } unlink $err_file; return ( $err, @result ); } # Demonstration. my $pass = 'password'; my $ip = 'ip_address'; my $cmd = 'uptime'; my ($err, @result) = do_cmd("sshpass -p $pass ssh user\@$ip $cmd"); if (length $err) { print "ERROR: $err\n"; } else { chomp @result; }

In reply to Re: getting STDERR from external command using OPEN by marioroy
in thread getting STDERR from external command using OPEN by gabrielsousa

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or or How to display code and escape characters are good places to start.
Log In?

What's my password?
Create A New User
Domain Nodelet?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (5)
As of 2021-10-20 10:15 GMT
Find Nodes?
    Voting Booth?
    My first memorable Perl project was:

    Results (80 votes). Check out past polls.