繁体   English   中英

具有多个参数的Perl系统命令输出到文件

[英]Perl system command with multiple parameters output to file

我需要使用以下形式调用系统命令:

system( $cmd, @args );

当我将@args定义为

my @args = ( "input1", "input2", ">", "file.out" );

“>”和“ file.out”并没有按照我的期望进行解释。 如何将这种形式的系统命令的输出发送到文件?

它将四个参数传递给程序,就像您在shell中执行了以下操作一样:

 prog "input1" "input2" ">" "file.out"

您不能指示外壳不使用外壳来重定向输出!

假定以下解决方案:

my $prog = 'cat';
my @args = ( 'input1', 'input2' );
my $out_qfn = 'file.out';

以下解决方案都缺少一些错误检查。

解决方案1

使用外壳执行重定向和转义。

system('/bin/sh', '-c', '"$@" > "$0"', $out_qfn, $prog, @args);

解决方案2

使用外壳执行重定向,并使用Perl执行转义。

use String::ShellQuote qw( shell_quote );

my $cmd = shell_quote($prog, @args) . " >".shell_quote($out_qfn);
system('/bin/sh', '-c', $cmd);

最后一行简化为

system($cmd);

解决方案3

避免使用外壳。 使用Perl执行重定向。

# This isn't safe if @args is empty.

open(my $out_fh, '>', $out_qfn)
   or die("Can't create output file \"$out_qfn\": $!\n");

open(my $pipe, '-|', $prog, @args)
   or die $!;

while (<$pipe>) {
   print($out_fh $_);
}

close($fh);

要么

# This isn't safe if @args is empty.

use IPC::Open3 qw( open3 );

{
   open(local *CHILD_STDIN, '<', '/dev/null')
      or die $!;

   open(local *CHILD_STDOUT, '>', $out_qfn)
      or die("Can't create output file \"$out_qfn\": $!\n");

   my $pid = open3('<&CHILD_STDIN', '>&CHILD_STDOUT', '>&STDERR', $prog, @args);
   waitpid($pid, 0);
}

要么

use IPC::Run3 qw( run3 );

run3([ $prog, @args ], \undef, $out_qfn);

要么

use IPC::Run qw( run );

run([ $prog, @args ], \undef, $out_qfn);

这是因为> file.out是Shell功能。 通过使用system在你的方式-你绕过外壳,并直接喂养的参数,我们在调用程序。

注意,参数处理根据参数的数量而变化。 如果LIST中有多个自变量,或者LIST是具有多个值的数组,请启动列表中第一个元素给出的程序,并使用列表其余部分给出的参数。 如果只有一个标量参数,则检查该参数是否包含shell元字符,如果有,则将整个参数传递到系统的命令shell进行解析(在Unix平台上为/ bin / sh -c,但在其他平台)。 如果参数中没有外壳元字符,则将其拆分为单词,然后直接传递给execvp,这样效率更高。 在Windows上,只有系统的PROGRAM LIST语法才能可靠地避免使用Shell。 如果第一个生成失败,即使有多个元素,系统LIST也会退回到Shell。

因此,重定向不起作用-大概您的程序正在忽略或处理>file.out传递的参数。

您可以执行一行“系统”:

system ( "$cmd @args" );

或使用open打开文件句柄,然后在程序中执行IO。

暂无
暂无

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

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