简体   繁体   English

Perl:如何将打开命令的输出传递给文件

[英]Perl: How to pipe output of an open command to a file

I want to run a program and pipe its output to a file. 我想运行一个程序并将其输出传递给一个文件。 The program could run for several hours, so i want to log all the data that happens while the program is running. 该程序可能会运行几个小时,所以我想记录程序运行时发生的所有数据。 How would i do it? 我该怎么办?

So in perl i have done this so far. 所以在Perl中我到目前为止已经这样做了。 As an example, i'm using ifconfig as my program. 作为一个例子,我使用ifconfig作为我的程序。 So in this case i want to output the ifconfig to a file. 所以在这种情况下我想将ifconfig输出到一个文件。 But the below code is outputting to STDOUT. 但是下面的代码输出到STDOUT。 How do i redirect the output to a text file? 如何将输出重定向到文本文件?

my $program1 = "/sbin/ifconfig";
open my $print_to_file, "|-", $program1, @args;
print $print_to_file;
close($print_to_file);

怎么样:

`$program @args > outfile`

In your example, $print_to_file is an input handle (it is the output stream of the external program, but your Perl script reads from it). 在您的示例中, $print_to_file是一个输入句柄(它是外部程序的输出流,但您的Perl脚本从中读取)。 So read from it and write its contents to a file through an output filehandle: 所以从中读取并通过输出文件句柄将其内容写入文件:

open my $read_from_cmd, "|-", $program1, @args;   # an input handle
open my $print_to_file, '>', $the_file;           # an output handle
print $print_to_file <$read_from_cmd>;
close $read_from_cmd;
close $print_to_file;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM