【发布时间】:2009-08-05 22:26:40
【问题描述】:
我运行了一些 bash 脚本,但它们可能需要几个小时才能完成,在此期间它们会喷出下载速度、ETA 和类似信息。我需要在 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,但它正在进行重大重构,不会立即解决您的问题。)