首页 文章

将STDOUT和STDERR重定向到文件,系统的标准输出/错误除外()

提问于
浏览
3

我试图在Linux中运行Perl脚本并使用以下命令将所有输出记录到STDOUT和STDERR到文件:

open (STDOUT, "| tee -i $transcript_file");
open (STDERR, "| tee -ai $transcript_file");

使用它的脚本大致如下:

  • 创建用于运行工具的环境 . 有很多 printwarn 和可能的 die 语句 .

  • 运行该工具(当前使用 system 命令) . 这会产生很多我希望出现在STDOUT上的输出,但不会出现在日志文件中(该工具会创建自己的日志文件) .

  • 分析结果,清理并退出 . 有很多 printwarn 和可能的 die 语句 .

一切正常,除了我想从日志中排除第2步的输出 . 有没有一种简单的方法来实现这一目标?

谢谢,

PS:这是我关于stackoverflow的第一个问题 . 如果我没有这样做,请帮我正确提问 .

2 回答

  • 0

    我同意Sobrique建议使用特殊功能 print_and_log . 但是如果你真的想按照你想要的方式去做,你可以 dup STDOUTSTDERR ,将它们重定向到你的日志然后使用 open3 来运行带有dup'ed原始标准输出和错误文件描述符的工具

    use  IPC::Open3;
    
    # dup the old standard output and error 
    open(OLDOUT, ">&STDOUT") or die "Can't dup STDOUT: $!\n";
    open(OLDERR, ">&STDERR") or die "Can't dup STDERR: $!\n";
    
    # reopen stdout and stderr
    open (STDOUT, "|tee $transcript_file") or die "Can't reopen STDOUT: $!\n";
    open (STDERR, ">&STDOUT")              or die "Can't reopen STDERR: $!\n";
    
    # print statements now write to log
    print "Logging important info: blah!\n";
    print STDERR "OOPS!\n";
    
    # run your command; output will go to original stdout
    # this will die() instead of returning say -1, so use eval() to catch errors
    my $pid = open3(">&OLDOUT", "<&STDIN", ">&OLDERR", $command); 
    
    # wash those dishes....
    waitpid( $pid, 0 );
    
  • 4

    鉴于你正在重新分配 STDINSTDOUT ,那么简短的回答是否定的 . 您正在捕获 STDOUT 上的所有内容,其中包括您的中间输出 .

    您可能会关闭/重新打开 STDOUT ,因为您没有建议't want it logging. But I'建议您可能要考虑之后的事情是什么?'re trying to accomplish - would a ' print_and_log ' subroutine do what you'?

相关问题