Hatena::Groupcside

Cside::StudyMemo このページをアンテナに追加 RSSフィード

メインブログに書くまでもない自分用メモを垂れ流す。日々是勉強也。

カテゴリー
 | 

2011-11-01

[]ちょっとずつ出力がされるコマンドの実行結果を出力のたびに受けとる

【追記】すみませんこれ IPC::Cmd::run_forked でできました。

use IPC::Cmd qw(run_forked);

my $cmd = "wget http://b.hatena.ne.jp/}";
my $result = run_forked(
    $cmd, {   
    stdout_handler => sub { print "[out]".shift },
    stderr_handler => sub { print "[err]".shift },
});

See Also




ということをしたかったので久々にAEを使ってみたメモ。

#!perl
use 5.12.0;
use warnings;

use AnyEvent;
use AnyEvent::Handle;

my $cv = AE::cv;

# ちょっとずつ出力がされるコマンド(何でもいい)
open(my $fh, "wget 'http://b.hatena.ne.jp' 2>&1 |");

my $handle; $handle = AnyEvent::Handle->new(
    fh => $fh,
    on_error => sub {
        undef $handle;
        $cv->send;
    },  
);
my $w; 
my $read; $read = sub {
    $handle->push_read(line => sub {
        my ($handle, $line) = @_; 
        say "received: $line";
        $w = AE::timer(0, 0, $read);
    }); 
};
$w = AE::timer(0, 0, $read);

$cv->recv;

実行結果

received: --2011-11-01 20:12:46--  http://b.hatena.ne.jp/
received: Resolving b.hatena.ne.jp... 59.106.194.17, 59.106.194.16
received: Connecting to b.hatena.ne.jp|59.106.194.17|:80... connected.
received: HTTP request sent, awaiting response... 200 OK
received: Length: 301465 (294K) [text/html]
received: Saving to: `index.html.36'
received:
received:      0K .......... .......... .......... .......... .......... 16% 94.4K 3s
received:     50K .......... .......... .......... .......... .......... 33%  241K 1s
received:    100K .......... .......... .......... .......... .......... 50%  522K 1s
received:    150K .......... .......... .......... .......... .......... 67%  987K 0s
received:    200K .......... .......... .......... .......... .......... 84%  252K 0s
received:    250K .......... .......... .......... .......... ....      100% 94.9M=1.1s
received:
received: 2011-11-01 20:12:48 (272 KB/s) - `index.html.36' saved [301465/301465]
received:
 |