2012-09-28 23 views
1

我試圖使用Expect與長時間運行的交互式進程交談。我正在使用cat -un來模擬這個過程。我的代碼如下:使用Perl與程序進行通信期望

#!/usr/bin/perl 

    use strict; 
    use warnings; 
    use Expect; 

    my $timeout = 4000; 

    my $exp = Expect->spawn("cat -un"); 

    my $text = <STDIN>; 
    $exp->send($text); 

    $text = <STDIN>; 
    $exp->send($text); 

    $exp->expect(undef); # Forever until EOF 
    $exp->expect($timeout); # For a few seconds 
    $exp->expect(0); 

    $text = <STDIN>; 
    $exp->send($text); 

    $exp->expect(undef); # Forever until EOF 
    $exp->expect($timeout); # For a few seconds 
    $exp->expect(0); 

我按第一個字符串+輸入並得到沒有輸出(顯然)。我輸入第二個字符串並按下cat -un轉儲到屏幕上的enter和stdout。我的第三個字符串不會產生任何輸出,但我希望它將stdout轉儲到屏幕上。

我的目標是與在屏幕上放置文本(要求用戶從菜單中進行選擇)的交互式過程進行交流,然後讓用戶輸入響應並將其發送到流程(這會生成更多輸出和更多菜單)。

期待似乎是最簡單的方法來做到這一點。請幫我。

回答

0

我並沒有完全想到你正在做的事情,但我確實想出了這個例子,它產生了"cat -un",然後等待通過<STDIN>輸入。每次接收到輸入時,它都會將該輸入發送到"cat -n",然後返回並等待更多輸入。如果您提供的意見或問題,我可以嘗試,並進一步解決您的問題更多信息

% ./myexpect.pl 
s1       <---- my input 
s1 
    1 s1 
1. sent text -> s1 
s2       <---- my input 
s2 
    2 s2 
2. sent text -> s2 
s3       <---- my input 
s3 
    3 s3 
3. sent text -> s3 
s4       <---- my input 
s4 
    4 s4 
4. sent text -> s4 
Ctrl-C      <---- my input 
% 

#!/usr/bin/perl 

use strict; 
use warnings; 
use Expect; 

my $timeout = 5; 

my $exp = Expect->spawn("cat -un"); 

#$exp->debug(3); 
$exp->debug(0); 

my $text; 
my $idx = 1; 
while (1) { 
    $text = <STDIN>; 
    $exp->send($text); 
    $exp->expect(1); 

    print "$idx. sent text -> $text"; 
    $idx++; 
} 

運行該sript,輸出結果。

相關問題