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

查看:33
本文介绍了从 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?

推荐答案

其实正确的写法是:

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

如果没有错误,您将获得0",如果错误,您将获得-1".

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

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

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