$ cmd输出到文件中

时间:2010-08-04 18:35:33

标签: perl cmd

我有以下代码:

$cmd = system ("p4 change -o 3456789");

我想将更改列表的输出描述打印到文件中。

$cmd = system ("p4 change -o 3456789 > output_cl.txt"); 

会将输出写入output_cl.txt文件。

但是,无论如何通过$cmd获得输出?

open(OUTPUT, ">$output_cl.txt") || die "Wrong Filename";
print OUTPUT ("$cmd"); 

将0或1写入文件。如何从$cmd获取输出?

4 个答案:

答案 0 :(得分:2)

要将p4命令的输出存储到数组中,请使用qx

my @lines = qx(p4 change -o 3456789);

答案 1 :(得分:2)

除了使用qx// or backticks获取命令的整个输出之外,您还可以获得命令输出的句柄。例如

open my $p4, "-|", "p4 change -o 3456789"
  or die "$0: open p4: $!";

现在,您可以一次阅读$p4一行,并可能按照

进行操作
while (<$p4>) {
  print OUTPUT lc($_);  # no shouting please!
}

答案 2 :(得分:1)

您始终可以使用以下过程将输出直接转储到文件中。

1) dup 系统STDOUT文件描述符,2)open STDOUT,3)系统,4)将IO插槽复制回STDOUT:< / p>

open( my $save_stdout, '>&1' );              # dup the file
open( STDOUT, '>', '/path/to/output/glop' ); # open STDOUT
system( qw<cmd.exe /C dir> );                # system (on windows)
*::STDOUT = $save_stdout;                    # overwrite STDOUT{IO}
print "Back to STDOUT!";                     # this should show up in output

但是qx//可能就是你要找的东西。

参考:perlopentut


当然这可以概括为:

sub command_to_file { 
    my $arg = shift;
    my ( $command, $rdir, $file ) = $arg =~ /(.*?)\s*(>{1,2})\s*([^>]+)$/;
    unless ( $command ) { 
       $command = $arg;
       $arg     = shift;
       ( $rdir, $file ) = $arg =~ /\s*(>{1,2})\s*([^>]*)$/;
       if ( !$rdir ) { 
           ( $rdir, $file ) = ( '>', $arg );
       }
       elsif ( !$file ) { 
           $file = shift;
       }
    }
    open( my $save_stdout, '>&1' );
    open( STDOUT, $rdir, $file );
    print $command, "\n\n";
    system( split /\s+/, $command );
    *::STDOUT = $save_stdout;
    return;
}

答案 3 :(得分:1)

如果你发现为了获得一个命令的返回值,它的输出,或者如何处理不同的返回代码,或者忘记右移生成的代码,你需要记住你需要运行的东西,你需要{{} 3}},这使得所有这些,简单,简单:

use IPC::System::Simple qw(system systemx capture capturex);

my $change_num = 3456789;
my $output = capture(qw(p4 change -o), $change_num);