如何将 STDOUT 和 STDERR 重定向到变量
我想将 STDERR
和 STDOUT
重定向到变量。我这样做了。
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.
}
系统
的问题。我也希望捕获此调用的输出。
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.
}
The problem with system
. I want the output of this call to be captured too.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用Capture::Tiny!
use Capture::Tiny!
您是否正在寻求捕获变量中的输出?如果是这样,您可以使用反引号或
qx{}
进行适当的重定向。例如,您可以使用:(我碰巧在目录中有程序 pth1、pth2 和 pth3 - 它们都正常;pth4 及以上将错误写入 stderr;重定向是必要的。)
您应该始终检查操作是否成功,例如如
open()
。为什么这是必要的?因为写入变量需要进行写入的进程的合作 - 而
make
不知道如何合作。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:(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.)
You should always check the success of operations such as
open()
.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 一起使用。以下是我最喜欢的两个:
使用
select
:使用
local
:享受。
There are several ways to redirect and restore STDOUT. Some of them work with STDERR too. Here are my two favorites:
Using
select
:Using
local
:Enjoy.
为什么不
使用 IPC::Open3
?Why not
use IPC::Open3
?TLDR 答案
使用 Capture::Tiny;
< /strong>合并 STDOUT 和 STDERR
如果您想要
STDOUT
(来自print()
s)和STDERR
(来自warn()< /code>s) 进行合并,然后使用...
分离的 STDOUT 和 STDERR
如果希望将它们分离...
Eval
@result
的结果表示成功,成功为
[1 ]
,失败为[]
。 Tiny 有大量其他功能,您可以查看其他情况,例如代码引用等。但我认为上面的代码应该涵盖大多数 Perl 开发人员的需求。TLDR Answer
use Capture::Tiny;
Merged STDOUT and STDERR
If you want
STDOUT
(fromprint()
s) andSTDERR
(fromwarn()
s) to be merged, then use...Separated STDOUT and STDERR
If you want them separated...
Results of Eval
@result
indicates the success, with success being[1]
, and failure being[]
. Tiny has a ton of other functions that you can look through for other cases, like code references, etc.. But I think the code above should cover most of any Perl developer's needs.