2015-02-24 22 views
1

myb.py的Perl:打開/關閉捕獲返回代碼

import time 
import sys 


stime = time.time() 
run_until = 600 

cnt = 0 
while True: 
    dur = time.time() - stime 
    if dur > run_until: 
     break 

    cnt += 1 
    print cnt 
    time.sleep(1) 

    if cnt == 10: 
     sys.exit(2)   <---- capture 2 

mya.pl

use FileHandle; 

my $myexe = 'myb.py'; 
my $FH = FileHandle->new; 
open $FH, q{-|}, 
    "$myexe 2>&1" 
    or print "Cannot open\n"; 
process_output($FH); 
close $FH or warn $!; 

sub process_output { 
    my ($fh) = @_; 

    while (my $line = <$fh>) { 
     chomp $line; 
     print "$line\n"; 
    } 

} 

OUTPUT:

1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
Warning: something's wrong at ./mya.pl line 10. 

如果我行更改爲:

my $err = close $FH; 

它給我一個空白的$ err。

問題:如何從mya.pl中的myb.py中捕獲返回代碼2?

+0

http://perldoc.perl.org/functions/close.html指出'close'返回'false'。它不一定是'0'。我想,一個空白*在perl中是''false''。 – rubikonx9 2015-02-24 15:27:19

+0

@ g.tsh是的,我得到了那部分。但我想專門捕捉'2'。不是真的或假的。這是不適合打開/關閉組合? – ealeon 2015-02-24 15:28:54

+0

我已經使用capture_exec:http://search.cpan.org/~dagolden/IO-CaptureOutput-1.1103/lib/IO/CaptureOutput.pm來獲取stdout和退出代碼。我不知道如何用簡單的'open'來實現這一點。 – rubikonx9 2015-02-24 15:35:10

回答

4

open創建子女時,close的功能爲waitpid,並相應地設置$?

$ perl -e' 
    open(my $fh, "-|", @ARGV) 
     or die $!; 

    print while <$fh>; 

    close($fh); 
    if ($? == -1) { die $!; } 
    elsif ($? & 0x7F) { die "Killed by signal ".($? & 0x7F)."\n"; } 
    elsif ($? >> 8 ) { die "Exited with error ".($? >> 8)."\n"; } 
' perl -E' 
    $| = 1; 
    for (1..5) { 
     say; 
     sleep 1; 
    } 
    exit 2; 
' 
1 
2 
3 
4 
5 
Exited with error 2 
5

如在http://perldoc.perl.org/functions/close.html中記錄的,退出值可作爲$?的一部分獲得。但它可以更方便地使用包裝:

use IPC::System::Simple qw(capture $EXITVAL EXIT_ANY); 

my @output = capture([0,2], "$myexe 2>&1"); 
print @output; 
print "Program exited with value $EXITVAL\n"; 

[0,2]說,出口值0或2預計,和其他任何一個致命的錯誤;您可以改用EXIT_ANY

儘管如此,它並沒有在所有的輸出結束,而是在產生時輸出。

相關問題