2012-05-21 256 views
9

我正在執行Perl程序。無論打印在我的控制檯上,我想將 重定向到文本文件。如何將控制檯輸出重定向到文本文件

+7

爲什麼不這樣做的命令行:'perl的-w my_program.pl> output.txt'? –

+1

@PaulR我不能+1足夠。發佈這個答案 - 這是做到這一點的正確方法。 – Polynomial

+1

http://stackoverflow.com/questions/387702/how-can-i-hook-into-perls-print –

回答

16

爲此的首選方法是通過命令行處理重定向,例如,

perl -w my_program.pl > my_output.txt 

如果您還想包括stderr輸出,那麼你可以這樣做(假設你的shell是bash):

perl -w my_program.pl &> my_output.txt 
+0

已經嘗試過,但沒有工作。我在我的文件中使用STDERR ..... – Cindrella

+0

好的 - 看看上面的編輯 - 也需要一些時間來學習Linux的命令行基礎知識等。 –

+0

謝謝....在文件中我使用了開放的STDERR,'> output.txt';關閉STDERR;它的工作.... – Cindrella

10

在CLI中,您可以使用>,像這樣:

perl <args> script_name.pl > path_to_your_file 

如果你想在perl腳本中這樣做,在你打印任何東西之前添加下面的代碼:

open(FH, '>', 'path_to_your_file') or die "cannot open file"; 
select FH; 
# ... 
# ... everything you print should be redirected to your file 
# ... 
close FH; # in the end 
+0

已經厭倦了這個...不工作我在我的文件中使用了打印STDERR。 ... – Cindrella

+1

好吧,如果你有明確的打印到不同的文件句柄,你應該按照Paul R的建議遵循CLI方式,這個問題可能應該被標記爲'bash'或類似的東西,因爲它與Perl本身沒什麼關係 – ArtM

5

在Unix上,爲了捕獲到終端的所有內容,您需要重定向標準輸出和標準錯誤。

使用bash,命令酷似

$ ./my-perl-program arg1 arg2 argn > output.txt 2>&1 

C shell中,csh衍生物如tcsh和bash的較新版本理解

$ ./my-perl-program arg1 arg2 argn >& output.txt 

爲是指相同的東西。

Windows上的命令shell的語法類似於Bourne shell。

C:\> my-perl-program.pl args 1> output.txt 2>&1 

要建立這種重定向在你的Perl代碼,添加

open STDOUT, ">", "output.txt" or die "$0: open: $!"; 
open STDERR, ">&STDOUT"  or die "$0: dup: $!"; 

到您的程序’的可執行語句的開始。

1

如果你想在控制檯打印你的輸出和日誌,然後(如之前的任何打印語句)

open (STDOUT, "| tee -ai logs.txt"); 
print "It Works!"; 

最後一次打印後在腳本中添加此行到您的代碼

close (STDOUT); 

僅適用於錯誤信息,

open (STDERR, "| tee -ai errorlogs.txt"); 
相關問題