Get both STDOUT and STDERR of a program or script to a variable in perl [duplicate]

这一生的挚爱 提交于 2019-12-23 04:28:17

问题


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..


回答1:


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

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

When wrong command provided,

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

Error OutPut is,

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.

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

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

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

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() : When you want to pipe the command (as input or output) to your script.

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

BR, Jerry James



来源:https://stackoverflow.com/questions/46486567/get-both-stdout-and-stderr-of-a-program-or-script-to-a-variable-in-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!