How to redirect console output to a text file

后端 未结 4 2000
眼角桃花
眼角桃花 2020-12-31 17:15

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

相关标签:
4条回答
  • 2020-12-31 17:19

    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
    
    0 讨论(0)
  • 2020-12-31 17:19

    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.

    0 讨论(0)
  • 2020-12-31 17:29

    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
    
    0 讨论(0)
  • 2020-12-31 17:34

    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");
    
    0 讨论(0)
提交回复
热议问题