[英]perl using open3 to write to STDIN and capture STDOUT and STDERR
[英]How to capture both STDOUT and STDERR in two different variables using Backticks in Perl
假设我想用我的脚本运行一个带有反引号的外部程序,同时我想捕获STDOUT和STDERR但是在两个不同的变量中。 我怎样才能做到这一点? 如果我运行此脚本,请参阅...
my $cmd = `snmpwalk -v $version -c $community $hostname $oid`;
...如果没有错误一切正常但是如果命令引发错误,则该错误将打印在命令行上,我不希望发生这种情况。 我也想捕获错误。 屏幕上无需打印任何内容。 有任何想法吗?
你不需要一直到open3
,IIRC只适用于你需要读写外部命令的时候,甚至还有其他方法。
对于你的问题,我建议使用Capture::Tiny
,它可以从其块内运行的任何东西捕获(甚至发球)STDOUT和STDERR。 例如,根据您的问题:
#!/usr/bin/env perl
use strict;
use warnings;
use Capture::Tiny qw/capture/;
...
my ($stdout, $stderr) = capture {
system ( "snmpwalk -v $version -c $community $hostname $oid" );
};
另一个例子考虑这个功能代码:
#!/usr/bin/env perl
use strict;
use warnings;
use Capture::Tiny qw/capture/;
my ($stdout, $stderr) = capture {
system ( "echo 'hello'" );
system ( "date" );
warn "Arg1!";
};
print "STDOUT:\n$stdout";
print "STDERR:\n$stderr";
刚刚给了我:
STDOUT:
hello
Mon Dec 19 23:59:06 CST 2011
STDERR:
Arg1! at ./test.pl line 11.
使用反引号执行此操作的唯一方法是重定向到shell命令中的文件:
my $cmd = `snmpwalk -v $version -c $community $hostname $oid 2>error.dat`;
如果要在脚本中捕获STDERR,则需要IPC :: Open3而不是反引号
在Perl FAQ中,根据您的进度,您有不同的选项:
http://perldoc.perl.org/perlfaq8.html#How-can-I-capture-STDERR-from-an-external-command%3f
对于您想要做的事情来说,它是一个非常方便的包装器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.