作者frank1983 (What?)
看板Perl
標題Re: [問題] 請教如何實現下邊這種重定向﹖
時間Sat May 14 02:37:40 2011
※ 引述《herolee (hero)》之銘言:
: 1、首先希望把標準錯誤能夠重定向到標準輸出﹐類似shell的 2>&1
您可以使用 open STDERR, ">&STDOUT"
(請參考
http://perldoc.perl.org/functions/open.html )
: 2、希望能把所有標準輸出(已包含標準錯誤的內容)在屏幕打印的同時﹐
: 也輸出到某個文件中。
: 請問﹐上述功能用perl怎麼實現呢﹖我隻會bash下的辦法。。。
CPAN 上有一些 module 可以試試: File::Tee (不能在 Windows 上執行)、Tee、
IO::CaptureOutput 等
這些 module 都能將如 system() 的輸出也導到檔案 (跟 tee 的功能相同)
如果您只是想將 print、printf、syswrite 等輸出的結果同時導到檔案,而忽略
system() 等由子行程輸出的結果 (這可能需要透過 IPC)
則可以考慮使用 IO::Tee
您甚至可以自己利用 tie 實作一簡單的多工輸出的 file handle (事實上 IO::Tee 就是
用 tie 實作的)
Tee.pm 的內容為:
#!/usr/bin/perl
use warnings;
use strict;
package Tee;
sub TIEHANDLE {
my $class = shift;
my @fh = @_;
bless \@fh, $class;
}
sub WRITE {
my $this = shift;
syswrite $_, @_ for @$this;
}
sub PRINT {
my $this = shift;
print {$_} @_ for @$this;
}
sub PRINTF {
my $this = shift;
printf {$_} @_ for @$this;
}
1;
而主程式為:
#!/usr/bin/perl
use warnings;
use strict;
use Tee;
open my $log, '>', 'log.txt' or die;
tie *FH, 'Tee', \*STDOUT, $log;
select(*FH);
print "hello world!\n";
這時 "hello world!\n" 會同時輸出到 STDOUT 和檔案 log.txt
(請參考
http://perldoc.perl.org/perltie.html#Tying-FileHandles )
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 111.243.162.213
推 herolee:請問如何可以實時的捕捉system()系統調用這種的輸出呢﹖ 05/14 11:12
→ frank1983:前面提到的File::Tee、Tee、IO::CaptureOutput 都可以啊 05/14 16:31
→ frank1983:或者你真正要的只是 perl script.pl 2>&1 | tee log.txt 05/14 16:34
推 herolee:沒錯﹐perl | tee這種我是知道的﹐但是用的時候不直接。 05/14 23:22