1

我正在尝试使用 Expect 与一个长时间运行的交互式进程交谈。我正在使用 cat -un 来模拟该过程。我的代码如下:

    #!/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); 

我按第一个字符串 + enter 并没有得到任何输出(显然)。我输入第二个字符串,然后按回车键,从 cat -un 转储到屏幕的标准输出。我的第三个字符串不会产生任何输出,但我希望它也能将标准输出转储到屏幕上。

我的目标是与将文本放在屏幕上的交互式进程进行通信(要求用户从菜单中进行选择),然后让用户输入响应并将其发送到进程(生成更多输出和更多菜单)。

Expect 似乎是最简单的方法。请协助我。

4

1 回答 1

0

我并没有完全理解你想要做什么,但我确实想出了这个例子,它产生"cat -un"然后等待通过<STDIN>. 每次它接收到输入时,它都会将该输入发送到"cat -n",然后返回并等待更多输入。

#!/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++;
}

运行此脚本会产生以下输出:

% ./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
%

如果您提供更多信息作为评论或问题,我可以尝试进一步解决您的问题。

于 2012-12-30T04:42:29.430 回答