如何将控制台输出重定向到文本文件

Cin*_*lla 9 perl command-line

我正在执行一个Perl程序.无论在我的控制台上打印什么,我想将其重定向到文本文件.

Pau*_*l R 17

对此的首选方法是通过命令行处理重定向,例如

perl -w my_program.pl > my_output.txt
Run Code Online (Sandbox Code Playgroud)

如果你还想包含stderr输出,那么你可以这样做(假设你的shell是bash):

perl -w my_program.pl &> my_output.txt
Run Code Online (Sandbox Code Playgroud)

  • 为了将来参考,请注意,通常最好在命令行上进行重定向 - 这样您就不需要修改Perl代码,并且可以在不同的上下文中重复使用它而无需任何更改. (2认同)

Art*_*rtM 11

在CLI中,您可以使用>,如下所示:

perl <args> script_name.pl > path_to_your_file
Run Code Online (Sandbox Code Playgroud)

如果要在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
Run Code Online (Sandbox Code Playgroud)


Gre*_*con 6

在Unix上,要捕获到终端的所有内容,您需要重定向标准输出和标准错误.

使用bash,命令类似

$ ./my-perl-program arg1 arg2 argn > output.txt 2>&1
Run Code Online (Sandbox Code Playgroud)

C shell,bash csh等衍生产品tcsh以及bash的新版本都可以理解

$ ./my-perl-program arg1 arg2 argn >& output.txt
Run Code Online (Sandbox Code Playgroud)

意思是同样的事情.

Windows上命令shell的语法类似于Bourne shell.

C:\> my-perl-program.pl args 1> output.txt 2>&1
Run Code Online (Sandbox Code Playgroud)

要在Perl代码中设置此重定向,请添加

open STDOUT, ">", "output.txt" or die "$0: open: $!";
open STDERR, ">&STDOUT"        or die "$0: dup: $!";
Run Code Online (Sandbox Code Playgroud)

到程序的可执行语句的开头.