我有幾個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