How to redirect console output to a text file

2019-02-06 16:14发布

I am executing a Perl program. Whatever is being printed on my console, I want to redirect that to a text file.

4条回答
我欲成王,谁敢阻挡
2楼-- · 2019-02-06 16:42

If you want your output to be printed on console as well as logs then append this line to you code (e.g. before any print statements)

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

After last print in your script

close (STDOUT);

For error messages only,

open (STDERR, "| tee -ai errorlogs.txt");
查看更多
Evening l夕情丶
3楼-- · 2019-02-06 16:43

The preferred method for this is to handle redirection via the command line, e.g.

perl -w my_program.pl > my_output.txt

If you want to also include stderr output then you can do this (assuming your shell is bash):

perl -w my_program.pl &> my_output.txt
查看更多
手持菜刀,她持情操
4楼-- · 2019-02-06 16:58

On Unix, to capture everything that goes to your terminal, you want to redirect both the standard output and the standard error.

With bash, the command resembles

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

The C shell, csh derivatives such as tcsh, and newer versions of bash understand

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

to mean the same thing.

The syntax for the command shell on Windows resembles Bourne shell's.

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

To set up this redirection in your Perl code, add

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

to the beginning of your program’s executable statements.

查看更多
Luminary・发光体
5楼-- · 2019-02-06 17:01

In the CLI you can use >, like this:

perl <args> script_name.pl > path_to_your_file

If you want to do this inside the perl script, add this code before you print anything:

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
查看更多
登录 后发表回答