2010-04-16 72 views
2

我有文件的URL列表,我想下載它們:管道下載和處理文件在Unix/Linux操作系統環境下使用Perl

http://somedomain.com/foo1.gz 
http://somedomain.com/foo2.gz 
http://somedomain.com/foo3.gz 

我想要做的就是爲每個文件如下:

  1. 下載foo1.2 ..與wgetnohup並行。
  2. 每次完成下載過程將它們與myscript.sh

我有什麼時候是這樣的:

#! /usr/bin/perl 

@files = glob("foo*.gz"); 

foreach $file (@files) { 
    my $downurls = "http://somedomain.com/".$file; 
    system("nohup wget $file &"); 
    system("./myscript.sh $file >> output.txt"); 
} 

的問題是,不將文件下載完畢時,我不能告訴上面的管道。 所以現在它myscript.sh不能正確執行。

什麼是實現這一目標的正確途徑?

回答

1

嘗試組合使用&&的命令,以便第二個只在第一個成功完成後才運行。

system("(nohup wget $file && ./myscript.sh $file >> output.txt) &"); 
2

爲什麼要用perl來做到這一點。改用bash。以下僅爲示例。

#!/bin/bash 

for file in foo1 foo2 foo3 
do 
    wget http://samedomain.com/$file.gz . 

    if [ -f $file.gz ]; 
    then 
     ./myscript.sh $file.gz >> output.txt 
    fi 
done 
1

如果你想要並行處理,你可以自己動手分叉,或者使用內置模塊來爲你處理。嘗試Parallel::ForkManager。您可以在How can I manage a fork pool in Perl?中看到更多關於它的用法,但模塊的CPAN頁面將具有真正有用的信息。你可能想要這樣的東西:

use Parallel::ForkManager; 

my $MAX_PROCESSES = 8; # 8 parallel processes max 
my $pm = new Parallel::ForkManager($MAX_PROCESSES); 

my @files = glob("foo*.gz"); 

foreach $file (@all_data) { 
    # Forks and returns the pid for the child: 
    my $pid = $pm->start and next; 

    my $downurls = "http://somedomain.com/".$file; 
    system("wget $file"); 
    system("./myscript.sh $file >> output.txt"); 

    $pm->finish; # Terminates the child process 
} 

print "All done!\n"; 
+1

內部循環取自請求的例子,我建議檢查系統調用的返回值,以確保命令執行正確。你必須右移8才能獲得shell退出代碼。 if((system(「command」)>> 8)== 0){...} – kbenson 2010-04-16 16:50:30