How can I run a system command and die if anything is written to STDERR?

后端 未结 2 619
广开言路
广开言路 2021-01-23 19:23

I\'m writing a Perl script which uses an external script. The external script must run from a specific directory so I found the following useful:

use IPC::System         


        
2条回答
  •  既然无缘
    2021-01-23 19:51

    This is covered in the Perl FAQ.

    Presuming test_app is a program that outputs one line to stdout and one line to stderr:

    use IPC::Open3;
    use Symbol 'gensym';
    
    my($wtr, $rdr, $err);
    $err = gensym;
    
    my $pid = open3($wtr, $rdr, $err, 'test_app');
    
    waitpid($pid, 0);
    my $status = $? >> 8;
    
    my $stdout = <$rdr>;
    my $stderr = <$err>;
    
    print "out output: $stdout\n";
    print "err output: $stderr\n";
    
    print "Exit code: $status\n";
    

    EDIT: Per the request updated to include capturing the exit code. You could also have asked perldoc IPC::Open3 which says

    waitpid( $pid, 0 );
    my $child_exit_status = $? >> 8;
    

    And which you should read anyway for its cautions and caveats.

提交回复
热议问题