1

我使用 IPC::Run 从 cron 运行脚本中的外部可执行文件获取输出。我需要它能够根据即时输出进行过滤和做出决策。但问题是它不是即时给我输出,而是分几批输出 - 一次多行,只有在可执行文件运行一段时间后。是否有可能像我们在 grep 命令中使用 grep 命令一样刷新输出grep --line-buffered?我没有在所有 Perl 站点中看到正确的回答。这是我的脚本部分:

use IPC::Run qw( start pump finish );
...
my $externalExecRun = start \@executableAndParameters, \undef, \$executableStdout, \$executableStderr ;
while (42) {
    pump $externalExecRun;
    if ($executableStdout eq '' and $engineStderr eq '') {last;}
    WriteToLog("\$executableStdout: -->$executableStdout<--");              #This writes many lines at once
    WriteToLog("\$executableStderr: -->$executableStderr<--");
    $executableStdout = "";
    $executableStderr = "";
}
finish $externalExecRun;
4

1 回答 1

2

You can use IPC::Run's new_chunker to have it give you output on a line-by-line basis:

use warnings;
use strict;
use IPC::Run qw/ start new_chunker /;
use Data::Dump;

my $run = start ['perl','-le','print "a" x $_ for 1..180'],
    '>', new_chunker, \my $out, '2>', new_chunker, \my $err;
while (1) {
    $run->pump;
    last unless defined $out || defined $err;
    dd $out, $err;
    ($out,$err) = ();
}
$run->finish;

It's still possible that the external program won't output on a line-by-line basis, in which case, at least on *NIX, changing the first '>' into '>pty>' (as suggested by @ikegami in the comments) will hopefully help; or one of the links provided by @daxim.

于 2018-03-10T12:26:54.210 回答