如何使用AnyEvent :: Subprocess使外部命令的输出自动刷新?

时间:2019-05-07 08:52:47

标签: perl anyevent

我正在尝试使用AnyEvent::Subprocess监视外部命令的输出:

use feature qw(say);
use strict;
use warnings;

use AnyEvent::Subprocess;

my $job = AnyEvent::Subprocess->new(
    delegates     => [ 'StandardHandles', 'CompletionCondvar' ],
    code          => 'myscript.pl',
);
my $run = $job->run;
my $condvar = $run->delegate('completion_condvar');

$run->delegate('stdout')->handle->on_read(
    sub {
        my ( $handle ) = @_;
        my $line = $handle->rbuf;
        chomp $line;
        say "Got output: '$line'";
        $handle->rbuf = ""; # clear buffer
      }
);
my $done = $condvar->recv;

通常,我无权访问外部脚本的源代码,因此无法将诸如STDOUT->autoflush(1)之类的命令插入脚本(如果该脚本碰巧是Perl脚本)。

这是我用于测试的测试脚本:

myscript.pl

use feature qw(say);
use strict;
use warnings;

#STDOUT->autoflush(1);
sleep 1;
say "data 1";
sleep 1;
say "data 2";
sleep 1;
say "data 3";

myscript.pl完成后,输出立即全部输出。我想从myscript.pl开始打印每一行。如何在不修改myscript.pl的情况下完成此操作?

0 个答案:

没有答案