在 perl 中使用 bactticks 将外部命令的输出存储到变量

storing the output of a external command to a variable using bactticks in perl

我正在使用以下代码将外部命令的输出存储在变量中。但是当我打印错误时,我什么也没得到。

$error1 = `hadoop fs -copyFromLocal $src_dir $tgt_dir`;
print "$error1\n";  # --> prints nothing

` `中命令的输出为:

copyFromLocal: Cannot create file/user/file5._COPYING_. Name node is in safe mode.

存储输出有什么问题吗?

Perl 中的反引号仅捕获标准输出。如果 hadoop 将消息发送到标准错误,反引号将不会捕获它。请参阅 How can I capture STDERR from an external command? 的 perlfaq 答案,了解几种方法。最简单的是使用 2>&1:

将标准错误文件描述符重定向到标准输出文件描述符
$error1 = `hadoop fs -copyFromLocal $src_dir $tgt_dir 2>&1`;

Capture::Tiny等模块也很不错。