从Perl中的外部* nix命令获取STDOUT,STDERR和响应代码 [英] Getting STDOUT, STDERR, and response code from external *nix command in perl

查看:128
本文介绍了从Perl中的外部* nix命令获取STDOUT,STDERR和响应代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的Perl脚本中执行一个外部命令,将stdout和stderr的输出都放入我选择的$variable中,并将命令的退出代码放入$?变量中.

I want to execute an external command from within my Perl script, putting the output of both stdout and stderr into a $variable of my choice, and to get the command's exit code into the $? variable.

我在 perlfaq8 及其论坛,但它们不适用于我.奇怪的是,只要退出代码正确,我在任何情况下都不会得到sdterr的输出.

I went through solutions in perlfaq8 and their forums, but they're not working for me. The strange thing is that I don't get the output of sdterr in any case, as long as the exit code is correct.

我在Red Hat Linux 5上使用Perl版本5.8.8.

I'm using Perl version 5.8.8, on Red Hat Linux 5.

这是我正在尝试的示例:

Here's an example of what I'm trying:

my $cmd="less";
my $out=`$cmd 2>&1`;

my $out=qx($cmd 2>&1);

open(PIPE, "$cmd 2>&1|");

当命令成功运行时,我可以捕获标准输出.

When the command runs successfully, I can capture stdout.

我不想使用其他捕获模块.如何捕获外部命令的全部结果?

I don't want to use additional capture modules. How can I capture the full results of the external command?

推荐答案

实际上,正确的写法是:

Actually, the proper way to write this is:

#!/usr/bin/perl
$cmd = 'lsss';  
my $out=qx($cmd 2>&1);
my $r_c=$?;
print "output was $out\n";
print "return code = ", $r_c, "\n";

如果没有错误,您将得到一个"0",如果有错误,您将得到一个"-1".

You will get a '0' if no error and '-1' if error.

这篇关于从Perl中的外部* nix命令获取STDOUT,STDERR和响应代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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