[英]Perl - best way to trap exit status and capture log for an external command
需要运行和外部命令,将输出写入日志文件并捕获退出状态
my $cmd = "db2 \"insert into schema.tablea (id, name, city) values (99, 'Micheal', 'London')\" ";
open my $log, ">", "logfile.log";
my $rt = open(OUTPUT,"$cmd 2>&1 | " );
while (<OUTPUT>){
chomp;
print $log $_, "\n";
print $_, "\n";
}
close(OUTPUT);
close($log);
print "Exit status is $rt\n";
任何帮助都非常感谢。
close
这种句柄会设置$?
与system
一样。
die $! if $? == -1;
die "Killed by ".( $? & 0x7F ) if $? & 0x7F;
die "Exited with ".( $? >> 8 ) if $? >> 8;
如果您仍然要掏出钱,不妨考虑一下
use String::ShellQuote qw( shell_quote );
system("$cmd 2>&1 | tee ".shell_quote($log));
您可以使用Capture :: Tiny:
use Capture::Tiny ':all';
use File::Slurp;
use autodie;
($stdout, $stderr, $exit) = tee sub {
system("echo hello; exit 15");
};
write_file('logfile.log', $stdout);
print "exit: ", $exit >> 8, "\n";
有关“ $ exit >> 8”的说明,请参见“ perldoc -f系统”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.