【问题标题】:perl open: how to forward stderr to stdout? [duplicate]perl open:如何将标准错误转发到标准输出? [复制]
【发布时间】:2012-12-06 08:28:32
【问题描述】:

可能重复:
How do you capture stderr, stdout, and the exit code all at once, in Perl?
Capturing the output of STDERR while piping STDOUT to a file

我正在使用以下代码来执行一个进程:

open( my $proch, "-|", $command, @arguments );

不幸的是,我只会阅读 stdout。但我也想阅读 stderr

Stderr 重定向导致如下错误:

open( my $proch, "2>&1 -|", $command, @arguments );
>>> Unknown open() mode '2>&1 -|' at file.pl line 289

如何将 stderr 转发到 stdout

【问题讨论】:

    标签: perl stdout stderr


    【解决方案1】:

    2>&1 是 shell 命令的一部分,但您没有执行 shell。

    open( my $proch, "-|", 'sh', '-c', '"$@" 2>&1', '--', $command, @arguments );
    

    如果你想避免产生额外的进程,你可以使用以下方法:

    use IPC::Open3 qw( open3 );
    
    open local *CHILD_STDIN, '<', '/dev/null') or die $!;
    my $pid = open3(
       '<&CHILD_STDIN',
       \local *PROCH,
       undef, # 2>&1
       $command, @arguments
    );
    
    while (<PROCH>) { ... }
    
    waitpid($pid, 0);
    

    【讨论】:

      猜你喜欢
      • 2011-03-09
      • 1970-01-01
      • 2012-10-19
      • 1970-01-01
      • 2019-09-03
      • 2015-02-19
      • 1970-01-01
      • 2019-05-22
      • 1970-01-01
      相关资源
      最近更新 更多