如何将 STDOUT 和 STDERR 重定向到变量 [英] How to redirect STDOUT and STDERR to a variable
问题描述
我想将 STDERR
和 STDOUT
重定向到一个变量.我做到了.
I want to redirect STDERR
and STDOUT
to a variable. I did this.
close(STDOUT);
close(STDERR);
my $out;
open(STDOUT, ">>", \$out);
open(STDERR, ">>", \$out);
for(1..10)
{
print "print\n"; # this is ok.
warn "warn\n"; # same
system("make"); # this is lost. neither in screen nor in variable.
}
system
的问题.我也希望捕获此调用的输出.
The problem with system
. I want the output of this call to be captured too.
推荐答案
您是否想在变量中捕获输出?如果是这样,您可以使用带有适当重定向的反引号或 qx{}
.例如,您可以使用:
Are you seeking to capture the output in a variable? If so, you have use backticks or qx{}
with appropriate redirection. For example, you could use:
#/usr/bin/env perl
use strict;
use warnings;
# Ensure we have a way to write messages
open my $fh, '>', "output" or die;
close(STDOUT);
close(STDERR);
my $out;
open(STDOUT, ">>", \$out) or do { print $fh, "failed to open STDOUT ($!)\n"; die };
open(STDERR, ">>", \$out) or do { print $fh, "failed to open STDERR ($!)\n"; die };
foreach my $i (1..10)
{
print "print $i\n";
warn "warn $i\n";
my $extra = qx{make pth$i 2>&1};
print $fh "<<$i>><<$out>><<$extra>>\n";
}
(我碰巧在目录中有 pth1、pth2 和 pth3 程序 - 它们被设置为正常;pth4 及以上将错误写入 stderr;重定向是必要的.)
(I happen to have programs pth1, pth2 and pth3 in the directory - they were made OK; pth4 and above write errors to stderr; the redirection was necessary.)
你应该经常检查open()
等操作是否成功.
You should always check the success of operations such as open()
.
为什么需要这样做?因为写入变量需要进行写入的进程的合作 - 而 make
不知道如何合作.
Why is this necessary? Because writing to a variable requires the cooperation of the process doing the writing - and make
doesn't know how to cooperate.
这篇关于如何将 STDOUT 和 STDERR 重定向到变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!