我有几个bash脚本运行,但是他们可能需要几个小时才能完成,在这段时间,他们会发出下载速度,ETA和类似的信息。我需要在perl中捕获这些信息,但是我遇到了一个问题,我无法逐行读取输出行(除非我错过了某些内容)。如何在Perl中实时读取外部命令的输出?
任何帮助解决这个问题?
编辑:解释这个更好一点我运行几个bash脚本沿彼此,我希望使用gtk与Perl产生方便的进度条。 目前,我为每个希望运行的bash脚本运行2个线程,一个用于更新图形信息的主线程。它看起来像这样(尽可能多地减少):
my $command1 = threads->create(\&runCmd, './bash1', \@out1);
my $controll1 = threads->create(\&monitor, $command1, \@out1);
my $command1 = threads->create(\&runCmd, 'bash2', \@out2);
my $controll2 = threads->create(\&monitor, $command2, \@out2);
sub runCmd{
my $cmd = shift;
my @bso = shift;
@bso = `$cmd`
}
sub monitor{
my $thrd = shift;
my @bso = shift;
my $line;
while($thrd->is_running()){
while($line = shift(@bso)){
## I check the line and do things with it here
}
## update anything the script doesn't tell me here.
sleep 1;# don't cripple the system polling data.
}
## thread quit, so we remove the status bar and check if another script is in the queue, I'm omitting this here.
}
你应该真的使用一个适当的事件循环,如POE,而不是线程。使用POE :: Wheel :: Run比使用手动滚动的几乎事件循环获得更好的成功。 (我会推荐AnyEvent :: Subprocess,但它正在进行一次重大的重构,并不会立即解决你的问题。) – jrockway 2009-08-06 16:12:33