如果将任何内容写入STDERR,如何运行系统命令而死? [英] How can I run a system command and die if anything is written to STDERR?
问题描述
我正在编写一个使用外部脚本的Perl脚本.外部脚本必须从特定目录运行,因此我发现以下有用:
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::Simple qw(capture);
my @args = ('external script path...', 'arg1', ...);
my $out = capture( [0], "cd $dir ; @args" );
有时,外部脚本会将内容写入STDERR,但仍返回0.我希望捕获这些时间和confess
(或die
).由于我无法控制外部脚本的返回值,因此我想也许可以捕获其STDERR,所以我将得到以下内容:
Sometimes the external script writes stuff to STDERR but still returns 0. I wish to capture these times and confess
(or die
). Since I don't control the return value of the external script, I thought maybe I could capture its STDERR so I'll have something like this:
my ($out, $err) = cool_capture( [0], "cd $dir ; @args" );
say "Output was: $out";
if ($err) {
die "Error: this was written to STDERR: $err";
}
我该怎么办?
推荐答案
这是假定test_app
是一个将一行输出到stdout并将一行输出到stderr的程序:
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";
根据更新的请求,其中包括捕获退出代码.您可能还问过perldoc IPC::Open3
上面写着
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.
这篇关于如果将任何内容写入STDERR,如何运行系统命令而死?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!