perl 如何抑制或重定向到系统命令的变量输出

h43kikqp  于 8个月前  发布在  Perl
关注(0)|答案(4)|浏览(90)

例如,我正在尝试执行系统命令

system('git clone .....' );
    if ($?) {
        croak('Error while cloning git repository');
    }

在这里,我检查结果是否成功,但如何不从系统命令输出错误,例如在我的情况下,我可以得到类似的东西

Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

执行命令。
我需要把这个错误放到变量中并抑制它(不要把它打印到终端)
然后检查此错误消息。
或者至少是压制它。
我需要用下面的方法测试这样的子程序

dies_ok { MyModule::sub_uses_system_command() } 'Died :(';

有可能得到这样的结果吗?
Thx提前

uajslkp6

uajslkp61#

system只返回执行的程序的退出状态,如果你想得到标准输出,你可以使用qx/command/或反引号来执行命令:

my $result = `git clone [...] 2>&1`

您应该注意,qx/command/和反引号形式的执行命令只返回STDOUT,因此如果您想捕获STDERR,则需要在命令中将STDERR重定向到STDOUT。

2nc8po8w

2nc8po8w2#

使用qx而不是system来捕获命令的输出。看起来你还想捕获stderr,所以使用标准的2>&1来dup stderr on to stdout。

$var = qx( git clone ... 2>&1 )
o2rvlv0m

o2rvlv0m3#

如果你需要做多个输出到STDERR/STDOUT的测试,你可以在一个块中重定向它们,并在其中运行所有这些测试。

sub use_system {
    system("asdfasdf asdfasdf");
    croak('this error') if $?;
}

{
    open my $stderr, '>', 'temp.fil' or die $!;
    local *STDERR = $stderr;

    dies_ok { use_system() } 'Died :(';

    # or even

    eval { use_system(); };

    like ($@, qr/this error/, "function failed with 'this error'");
}

warn "STDERR back to normal\n";
omvjsjqw

omvjsjqw4#

您可以重定向输出:

system(`git clone https://example.com/some/path >/dev/null 2>&1`);

如果命令是动态构建的(需要参数),system()可以说比qx//更好,因为你不需要参与插值和引用。你可以将参数传递给shell,并在-c的参数中使用它们作为shell变量:

system('sh', '-c', 'echo "$1" "$2" >/dev/null 2>&1', '-', $some, $args)

相关问题