Get both STDOUT and STDERR of a program or script

2019-06-10 20:38发布

This question already has an answer here:

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条回答
放荡不羁爱自由
2楼-- · 2019-06-10 21:15

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

查看更多
登录 后发表回答