【问题标题】:How to discard STDERR from an external command in Perl?如何从 Perl 的外部命令中丢弃 STDERR?
【发布时间】:2010-07-16 10:30:50
【问题描述】:

我想捕获外部命令的退出代码,同时将其标准错误输出替换为自定义错误消息。

my $ret = system("which mysql");
if ($ret != 0) {
    say "Error";
}

如果mysql 可执行文件不存在,它会显示which 命令错误消息,这是我不想要的。如何摆脱它?

【问题讨论】:

标签: perl


【解决方案1】:

http://perldoc.perl.org/perlfaq8.html#How-can-I-capture-STDERR-from-an-external-command%3f

如何从外部命令捕获 STDERR?

运行外部命令的三种基本方式:

system $cmd;        # using system()
$output = `$cmd`;       # using backticks (``)
open (PIPE, "cmd |");   # using open()

使用 system(),STDOUT 和 STDERR 将与脚本的 STDOUT 和 STDERR 放在同一个位置,除非 system() 命令重定向它们。反引号和 open() 仅读取命令的 STDOUT。 您还可以使用 IPC::Open3 中的 open3() 函数。 Benjamin Goldberg 提供了一些示例代码: 捕获程序的 STDOUT,但丢弃其 STDERR:

use IPC::Open3;
use File::Spec;
use Symbol qw(gensym);
open(NULL, ">", File::Spec->devnull);
my $pid = open3(gensym, \*PH, ">&NULL", "cmd");
while( <PH> ) { }
waitpid($pid, 0);

捕获程序的 STDERR,但丢弃其 STDOUT:

use IPC::Open3;
use File::Spec;
use Symbol qw(gensym);
open(NULL, ">", File::Spec->devnull);
my $pid = open3(gensym, ">&NULL", \*PH, "cmd");
while( <PH> ) { }
waitpid($pid, 0);

捕获程序的 STDERR,并让它的 STDOUT 转到我们自己的 STDERR:

use IPC::Open3;
use Symbol qw(gensym);
my $pid = open3(gensym, ">&STDERR", \*PH, "cmd");
while( <PH> ) { }
waitpid($pid, 0);

要分别读取命令的 STDOUT 和 STDERR,可以将它们重定向到临时文件,让命令运行,然后读取临时文件:

use IPC::Open3;
use Symbol qw(gensym);
use IO::File;
local *CATCHOUT = IO::File->new_tmpfile;
local *CATCHERR = IO::File->new_tmpfile;
my $pid = open3(gensym, ">&CATCHOUT", ">&CATCHERR", "cmd");
waitpid($pid, 0);
seek $_, 0, 0 for \*CATCHOUT, \*CATCHERR;
while( <CATCHOUT> ) {}
while( <CATCHERR> ) {}

但是两者都不是临时文件的真正需要......以下应该也可以工作,没有死锁:

use IPC::Open3;
use Symbol qw(gensym);
use IO::File;
local *CATCHERR = IO::File->new_tmpfile;
my $pid = open3(gensym, \*CATCHOUT, ">&CATCHERR", "cmd");
while( <CATCHOUT> ) {}
waitpid($pid, 0);
seek CATCHERR, 0, 0;
while( <CATCHERR> ) {}

而且它也会更快,因为我们可以立即开始处理程序的标准输出,而不是等待程序完成。 使用其中任何一个,您都可以在调用之前更改文件描述符:

open(STDOUT, ">logfile");
system("ls");

或者您可以使用 Bourne shell 文件描述符重定向:

$output = `$cmd 2>some_file`;
open (PIPE, "cmd 2>some_file |");

您还可以使用文件描述符重定向使 STDERR 成为 STDOUT 的副本:

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

请注意,您不能简单地在 Perl 程序中打开 STDERR 作为 STDOUT 的副本,并避免调用 shell 进行重定向。这不起作用:

open(STDERR, ">&STDOUT");
$alloutput = `cmd args`;  # stderr still escapes

这失败了,因为 open() 使 STDERR 转到在 open() 时 STDOUT 所在的位置。然后反引号使 STDOUT 转到一个字符串,但不要更改 STDERR(它仍然转到旧的 STDOUT)。 请注意,您必须在反引号中使用 Bourne shell (sh(1) ) 重定向语法,而不是 csh(1) !关于为什么 Perl 的 system() 和反引号和管道打开都使用 Bourne shell 的详细信息,请参见 http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz 的“远超你想知道的”集合中的 vs/csh.whynot 文章。一起捕获命令的 STDERR 和 STDOUT:

$output = `cmd 2>&1`;                       # either with backticks
$pid = open(PH, "cmd 2>&1 |");              # or with an open pipe
while (<PH>) { }                            #    plus a read

捕获命令的 STDOUT 但丢弃其 STDERR:

$output = `cmd 2>/dev/null`;                # either with backticks
$pid = open(PH, "cmd 2>/dev/null |");       # or with an open pipe
while (<PH>) { }                            #    plus a read

捕获命令的 STDERR 但丢弃其 STDOUT:

$output = `cmd 2>&1 1>/dev/null`;           # either with backticks
$pid = open(PH, "cmd 2>&1 1>/dev/null |");  # or with an open pipe
while (<PH>) { }                            #    plus a read

交换命令的 STDOUT 和 STDERR 以捕获 STDERR,但将其 STDOUT 留给我们旧的 STDERR:

$output = `cmd 3>&1 1>&2 2>&3 3>&-`;        # either with backticks
$pid = open(PH, "cmd 3>&1 1>&2 2>&3 3>&-|");# or with an open pipe
while (<PH>) { }                            #    plus a read

要分别读取命令的 STDOUT 和 STDERR,最简单的方法是将它们分别重定向到文件,然后在程序完成时从这些文件中读取:

system("program args 1>program.stdout 2>program.stderr");

在所有这些示例中,排序都很重要。这是因为 shell 严格按照从左到右的顺序处理文件描述符重定向。

system("prog args 1>tmpfile 2>&1");
system("prog args 2>&1 1>tmpfile");

第一个命令将标准输出和标准错误都发送到临时文件。第二个命令只在那里发送旧标准输出,旧标准错误显示在旧标准输出上。

【讨论】:

  • $output = cmd 2&gt;/dev/null;这只是答案。
  • 不,上面还有另一个答案,第一个例子。
  • 不,重定向技巧不是唯一的答案。在两种情况下,这是 错误 的答案:一种是命令包含 shell 元字符并且您想完全避免使用 shell(例如,通过向系统提供列表或打开);或者如果该命令包含来自不受信任来源的内容(shell 注入,有人吗?)
【解决方案2】:

更现代的 Perl 方法可能是使用诸如 Capture::Tiny 之类的模块。例如:

#!/usr/bin/perl
use strict;
use warnings;

use Capture::Tiny qw/capture/;

my $ret;

# you may ignore stdout/stderr, if you wish, by commenting out the next line
my ($stdout, $stderr) =
  capture {
    $ret = system("which mysql");
  };

if ($ret!=0) {
  print " error " ;
  # perhaps even something cool like
  # print $stderr if $verbose # where $verbose is set by a command-line flag.
}

【讨论】:

    猜你喜欢
    • 2012-02-02
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多