4

考虑以下 perl 脚本 ( read.pl):

my $line = <STDIN>;
print "Perl read: $line";
print "And here's what cat gets: ", `cat -`;

如果从命令行执行此脚本,它将获取第一行输入,同时cat获取其他所有内容,直到输入结束(^D按下)。

但是,当输入从另一个进程通过管道传输或从文件中读取时,情况就不同了:

$ echo "foo\nbar" | ./read.pl
Perl read: foo
And here's what cat gets:

Perl 似乎很容易在某处缓冲整个输入,并且使用反引号或系统调用的进程看不到任何输入。

问题是我想对一个混合<STDIN>并调用其他进程的脚本进行单元测试。最好的方法是什么?我可以在 perl 中关闭输入缓冲吗?或者我可以以“模仿”终端的方式假脱机数据吗?

4

5 回答 5

2

这不是 Perl 问题。这是一个 UNIX/shell 问题。当您在没有管道的情况下运行命令时,您处于行缓冲模式,但是当您使用管道重定向时,您处于块缓冲模式。你可以这样说:

cat /usr/share/dict/words | ./read.pl | head

这个 C 程序有同样的问题:

#include <stdio.h>

int main(int argc, char** argv) {
    char line[4096];
    FILE* cat;
    fgets(line, 4096, stdin);
    printf("C got: %s\ncat got:\n", line);
    cat = popen("cat", "r");
    while (fgets(line, 4096, cat)) {
        printf("%s", line);
    }
    pclose(cat);
    return 0;
}
于 2010-09-13T11:13:12.773 回答
2

我有好消息和坏消息。

好消息是一个简单的修改read.pl允许你给它假输入:

#! /usr/bin/perl

use warnings;
use strict;

binmode STDIN, "unix" or die "$0: binmode: $!";

my $line = <STDIN>;
print "Perl read: $line";
print "And here's what cat gets: ", `cat -`;

样品运行:

$ printf "A\nB\nC\nD\n" | ./read.pl
Perl 读取:A
这就是猫得到的:B
C
D

坏消息是你得到一个单一的切换:如果你尝试重复 read-then-cat,第一个cat将饿死所有后续的读取。要看到这一点,请考虑

#! /usr/bin/perl

use warnings;
use strict;

binmode STDIN, "unix" or die "$0: binmode: $!";

my $line = <STDIN>;
print "1: Perl read: $line";
print "1: And here's what cat gets: ", `cat -`;
$line = <STDIN>;
$line = "<undefined>\n" unless defined $line;
print "2: Perl read: $line";
print "2: And here's what cat gets: ", `cat -`;

然后是产生的样本运行

$ printf "A\nB\nC\nD\n" | ./read.pl
1:Perl 读取:A
1:这就是猫得到的:B
C
D
2:Perl 读取:<未定义>
2:这就是猫得到的:
于 2010-09-13T13:36:27.193 回答
2

今天我想我找到了我需要的东西:Perl 有一个名为Expect的模块,它非常适合这种情况:

#!/usr/bin/perl

use strict;
use warnings;

use Expect;

my $exp = Expect->spawn('./read.pl');
$exp->send("First Line\n");
$exp->send("Second Line\n");
$exp->send("Third Line\n");
$exp->soft_close();

奇迹般有效 ;)

于 2010-09-15T11:38:23.947 回答
0

这是我发现的一种次优方式:

use IPC::Run;

my $input = "First Line\n";
my $output;
my $process = IPC::Run::start(['./read.pl'], \$input, \$output);
$process->pump() until $output =~ /Perl read:/;
$input .= "Second Line\n";
$process->finish();
print $output;

从某种意义上说,在等待更多输入之前需要知道程序将发出的“提示”是次优的。

另一个次优解决方案如下:

use IPC::Run;

my $input = "First Line\n";
my $output;
my $process = IPC::Run::start(['./read.pl'], \$input, my $timer = IPC::Run::timer(1));
$process->pump() until $timer->is_expired();
$timer->start(1);
$input .= "Second Line\n";
$process->finish();

它不需要任何提示知识,但速度很慢,因为它至少要等待两秒钟。另外,我不明白为什么需要第二个计时器(否则完成不会返回)。

有人知道更好的解决方案吗?

于 2010-09-13T09:21:32.453 回答
0

最后我得到了以下解决方案。仍然远未达到最佳状态,但它确实有效。即使在gbacon 所描述的情况下也是如此。

use Carp qw( confess );
use IPC::Run;
use Scalar::Util;
use Time::HiRes;

# Invokes the given program with the given input and argv, and returns stdout/stderr.
#
# The first argument provided is the input for the program. It is an arrayref
# containing one or more of the following:
# 
# * A scalar is simply passed to the program as stdin
#
# * An arrayref in the form [ "prompt", "input" ] causes the function to wait
#   until the program prints "prompt", then spools "input" to its stdin
#
# * An arrayref in the form [ 0.3, "input" ] waits 0.3 seconds, then spools
#   "input" to the program's stdin
sub capture_with_input {
    my ($program, $inputs, @argv) = @_;
    my ($stdout, $stderr);
    my $stdin = '';

    my $process = IPC::Run::start( [$program, @argv], \$stdin, \$stdout, \$stderr );
    foreach my $input (@$inputs) {
        if (ref($input) eq '') {
            $stdin .= $input;
        }
        elsif (ref($input) eq 'ARRAY') {
            (scalar @$input == 2) or
                confess "Input to capture_with_input must be of the form ['prompt', 'input'] or [timeout, 'input']!";

            my ($prompt_or_timeout, $text) = @$input;
            if (Scalar::Util::looks_like_number($prompt_or_timeout)) {
                my $start_time = [ Time::HiRes::gettimeofday ];
                $process->pump_nb() while (Time::HiRes::tv_interval($start_time) < $prompt_or_timeout);
            }
            else {
                $prompt_or_timeout = quotemeta $prompt_or_timeout;
                $process->pump until $stdout =~ m/$prompt_or_timeout/gc;
            }

            $stdin .= $text;
        }
        else {
            confess "Unknown input type passed to capture_with_input!";
        }
    }
    $process->finish();

    return ($stdout, $stderr);
}

my $input = [
    "First Line\n",
    ["Perl read:", "Second Line\n"],
    [0.5, "Third Line\n"],
];
print "Executing process...\n";
my ($stdout, $stderr) = capture_with_input('./read.pl', $input);
print "done.\n";
print "STDOUT:\n", $stdout;
print "STDERR:\n", $stderr;

使用示例(稍微修改 read.pl 来测试 gbacon 的情况):

$ time ./spool_read4.pl
Executing process...
done.
STDOUT:
Perl read: First Line
And here's what head -n1 gets: Second Line
Perl read again: Third Line

STDERR:
./spool_read4.pl  0.54s user 0.02s system 102% cpu 0.547 total

不过,我愿意接受更好的解决方案......

于 2010-09-14T07:50:51.867 回答