将程序或脚本的STDOUT和STDERR都获取到perl中的变量 [英] Get both STDOUT and STDERR of a program or script to a variable in perl

查看:110
本文介绍了将程序或脚本的STDOUT和STDERR都获取到perl中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了很多Google工作,将程序的STDOUT和STDERR都重定向到Perl中的变量,最初我尝试同时使用 open 反引号,但是未能捕获对变量的错误信号。

I did lot of google to redirect the both STDOUT and STDERR of a program to a variable in perl, Initially i tried using both open and backticks, but failed to capture Error signal to the variable.

我发布此问题是因为现在我有了解决方案,希望它可以对其他人有所帮助。

I am posting this question because Now I got the solution and hope it may helps others..

推荐答案

要将STDOUT和STDERR都转换为变量,请使用反引号(``)遵循以下代码片段。

To get both STDOUT and STDERR into a variable use following code snippet using backticks (``).

确保 2>& 1 位于命令末尾,以将STDERR重定向到STDOUT。

Make sure 2>&1 is places at the end of your command, to redirect STDERR in to STDOUT.

何时提供的命令错误,

my $Temp_return;
$Temp_return = `lse 2>&1`;
print "return = " . $Temp_return . "\n";

错误输出为,

return = 'lse' is not recognized as an internal or external command, operable program or batch file.

对于正确的命令,您将得到相应的结果。

For correct command you will get the result accordingly.

作为附加信息,在Perl中执行命令的方法也不同。

As an additional information different methods for executing the command in Perl are.

system()::如果要执行命令,对读取已执行命令的控制台输出不感兴趣。

system() : If you want to execute a command and not interested in reading console output of the executed command.

exec:当您不想返回到调用Perl脚本时。

exec : When you don't want to return to the calling Perl script. use same.

反引号::当您要将命令的控制台输出存储/读取到Perl变量中时。最初我错误地认为,需要使用Single cores('')来反引号('')并感到困惑,因为它几乎与Single cores('')相似,请注意。

backticks : When you want to store /read the console output of the command into a Perl variable. Initial I mistakenly thought, required to use Single cores('') instead, for backticks (``) and get confused, because its almost similar to Single cores(''), please give attention.

open()::要将管道(作为输入或输出)传递到脚本中时。

open() : When you want to pipe the command (as input or output) to your script.

希望对您有帮助.....:)

Hope it could be helpful for you..... :)

BR,
Jerry James

BR, Jerry James

这篇关于将程序或脚本的STDOUT和STDERR都获取到perl中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆