将STDOUT和STDERR重定向到文件,但system()的标准输出/错误除外 [英] Redirecting STDOUT and STDERR to a file, except for standard output/error of system()

查看:176
本文介绍了将STDOUT和STDERR重定向到文件,但system()的标准输出/错误除外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to run a Perl script in Linux and log all output to STDOUT and STDERR to a file using:

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

使用此脚本的脚本大致如下:

The script that uses this works roughly as follows:

  1. 创建用于运行工具的环境.有很多printwarn和可能的die语句.
  2. 运行该工具(当前使用system命令).这会产生很多输出,但我希望这些输出显示在STDOUT上,而不是显示在日志文件中(该工具会创建自己的日志文件).
  3. 分析结果,清理并退出.有很多printwarn和可能的die语句.
  1. Create an environment for running a tool. Has many print, warn and possibly die statements.
  2. Run the tool (Currently using system command). This produces a lot of output which I want to appear on STDOUT, but not in the logfile (The tool creates its own logfile).
  3. Analyze the results, cleanup and exit. Has many print, warn and possibly die statements.

一切正常,除了我想从日志中排除步骤2的输出.有没有简单的方法可以做到这一点?

Everything works correctly except I would like to exclude the output of step 2 from the log. Is there a simple way to achieve this?

谢谢

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

PS: This is my first question on stackoverflow. Please help me in asking questions correctly if I have not done so.

推荐答案

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

I agree with Sobrique's advice to use a special function print_and_log. But if you really want to do it the way you set out to do, you can dup STDOUT and STDERR, redirect them to your log and then use open3 to run your tool with the dup'ed original standard output and error file descriptors

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 );

这篇关于将STDOUT和STDERR重定向到文件,但system()的标准输出/错误除外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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