我要发送命令,例如执行ping操作:
ping google.es -n 500
我可以执行以下命令:
my $command = "ping google.es -n 500";
system($command);
我将在运行时打印输出。
我可以使用以下方法将其存储到变量中:
my $command = "ping google.es -n 500";
my $output = `$command`;
但是如何获取命令运行中的输出,然后在变量中使用输出?
我已经看到了这样的解决方案,但是它不起作用。它运行脚本,并且完成后将打印结果:
my $variable = '';
open my $command_pipe, "-|", $command or die "Pipe from $command failed: $!";
while (<$command_pipe>) {
print $_;
$variable . = $_;
}
更新: 示例来显示问题。我有2个Perl脚本,一个叫另一个:
test.pl:
use strict;
use warnings;
my $command = 'perl test2.pl';
print "Localtime: " . localtime() . "\n";
my $variable = '';
open my $command_pipe, "-|", $command or die "Pipe from $command failed: $!";
while (<$command_pipe>) {
print "[" . localtime() . "] " . $_;
$variable .= $_;
}
print "Localtime: " . localtime() . "\n";
print "Loop finished:\n$variable\n";
第二个文件test2.pl:
use strict;
use warnings;
print "Waiting 10 sec\n";
my $i = 0;
while($i < 10){
sleep(1);
print "$i\n";
$i++;
}
print "That's it!\n";
输出为:
C:\Users\****\Desktop\****>perl test.pl
Localtime: Wed Oct 17 13:47:06 2018
[Wed Oct 17 13:47:16 2018] Waiting 10 sec
[Wed Oct 17 13:47:16 2018] 0
[Wed Oct 17 13:47:16 2018] 1
[Wed Oct 17 13:47:16 2018] 2
[Wed Oct 17 13:47:16 2018] 3
[Wed Oct 17 13:47:16 2018] 4
[Wed Oct 17 13:47:16 2018] 5
[Wed Oct 17 13:47:16 2018] 6
[Wed Oct 17 13:47:16 2018] 7
[Wed Oct 17 13:47:16 2018] 8
[Wed Oct 17 13:47:16 2018] 9
[Wed Oct 17 13:47:16 2018] That's it!
Localtime: Wed Oct 17 13:47:16 2018
Loop finished:
Waiting 10 sec
0
1
2
3
4
5
6
7
8
9
That's it!
如您所见,所有内容都在第二个脚本的10秒后打印完毕。
答案 0 :(得分:6)
此代码完全符合我的预期(我稍微更改了您的ping
调用的语法)。
#!/usr/bin/perl
use strict;
use warnings;
my $command = 'ping -c 5 google.es';
my $variable;
open my $command_pipe, "-|", $command or die "Pipe from $command failed: $!";
while (<$command_pipe>) {
print $_;
$variable .= $_;
}
print "Loop finished:\n$variable\n";
如果它不适合您,则您可能是Suffering from Buffering。另外,您能否给我们提供一个完整的,自包含的程序来演示您的问题?
更新:如上所述,您正在遭受缓冲。您是否阅读了我链接的文章?您需要做的就是关闭STDOUT上的缓冲。
$|++;
更新2:为清楚起见,您需要将该代码放在test2.pl
中-这是正在执行缓冲打印的程序,因此需要关闭缓冲。< / p>