[英]Perl: avoid greedy reading from stdin?
考虑以下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中关闭输入缓冲吗? 或者我可以以“模仿”终端的方式假脱机数据吗?
这不是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;
}
我有好消息和坏消息。
好消息是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 read: A And here's what cat gets: B C D
坏消息是你得到一次转换:如果你试图重复读取当时的猫,那么第一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 read: A 1: And here's what cat gets: B C D 2: Perl read: <undefined> 2: And here's what cat gets:
今天我想我已经找到了我需要的东西: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();
奇迹般有效 ;)
这是我发现的次优方式:
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();
它不需要任何提示的知识,但是因为它等待至少两秒钟而很慢。 另外,我不明白为什么需要第二个计时器(完成后不会返回)。
有人知道更好的解决方案吗?
最后我得到了以下解决方案。 仍然远非最佳,但它的工作原理。 即使在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
不过,我愿意接受更好的解决方案......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.