问题描述
我正在尝试在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:
- 创建用于运行工具的环境.有很多
print
,warn
和可能的die
语句. - 运行该工具(当前使用
system
命令).这会产生很多输出,但我希望这些输出显示在STDOUT上,而不是显示在日志文件中(该工具会创建自己的日志文件). - 分析结果,清理并退出.有很多
print
,warn
和可能的die
语句.
- Create an environment for running a tool. Has many
print
,warn
and possiblydie
statements. - 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). - Analyze the results, cleanup and exit. Has many
print
,warn
and possiblydie
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
STDOUT
和STDERR
,将它们重定向到日志,然后使用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()的标准输出/错误除外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!