显示和捕获标准输出
Display AND Capture STDOUT
在我看来,我正在做的事情似乎应该相当简单,所以我可能会在回答后被打脸。话虽这么说:
我正在尝试从我的 PERL 脚本中调用外部(非 PERL)函数。我希望将函数的 STDOUT 打印到控制台(当它发生时),我还想捕获该信息并将其 return 到调用它的原始 PERL 脚本。
尝试过的解决方案包括:
#does not return the output
my @output = system($cmd);
#does not display the output as it occurs
my @output = `$cmd`;
#does not display the output as it occurs
eval {$pid = open3($Input, $Output, $Error, $cmd); }; die "open3: $@\n" if $@;
有谁知道既可以将 STDOUT 打印到屏幕(实时)又可以捕获 STDOUT 并将其return 发送到调用的原始来源的方法?
Capture::Tiny 可以做到。您可以之后自己 capture_stdout
和 print
,或者使用 tee_stdout
让它同时打印和捕获。
use strict;
use warnings;
use Capture::Tiny 'tee_stdout';
my $stdout = tee_stdout sub { `ls -lah` }; # prints
print "ok\n" if $stdout =~ m/\./; # matches
在我看来,我正在做的事情似乎应该相当简单,所以我可能会在回答后被打脸。话虽这么说:
我正在尝试从我的 PERL 脚本中调用外部(非 PERL)函数。我希望将函数的 STDOUT 打印到控制台(当它发生时),我还想捕获该信息并将其 return 到调用它的原始 PERL 脚本。
尝试过的解决方案包括:
#does not return the output
my @output = system($cmd);
#does not display the output as it occurs
my @output = `$cmd`;
#does not display the output as it occurs
eval {$pid = open3($Input, $Output, $Error, $cmd); }; die "open3: $@\n" if $@;
有谁知道既可以将 STDOUT 打印到屏幕(实时)又可以捕获 STDOUT 并将其return 发送到调用的原始来源的方法?
Capture::Tiny 可以做到。您可以之后自己 capture_stdout
和 print
,或者使用 tee_stdout
让它同时打印和捕获。
use strict;
use warnings;
use Capture::Tiny 'tee_stdout';
my $stdout = tee_stdout sub { `ls -lah` }; # prints
print "ok\n" if $stdout =~ m/\./; # matches