我想发送一个命令,例如,执行ping:
ping google.es -n 500
Run Code Online (Sandbox Code Playgroud)
我可以用以下命令执行命令:
my $command = "ping google.es -n 500";
system($command);
Run Code Online (Sandbox Code Playgroud)
我会在运行时打印输出.
我可以将它存储到变量中:
my $command = "ping google.es -n 500";
my $output = `$command`;
Run Code Online (Sandbox Code Playgroud)
但是如何获取命令的输出WHILE它正在运行,然后在变量中使用输出?
我看到这样的解决方案,但它不起作用.它运行脚本,完成后将打印结果:
my $variable = '';
open my $command_pipe, "-|", $command or die "Pipe from $command failed: $!";
while (<$command_pipe>) {
print $_;
$variable . = $_;
}
Run Code Online (Sandbox Code Playgroud)
更新:显示问题的示例.我有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";
Run Code Online (Sandbox Code Playgroud)
第二个文件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";
Run Code Online (Sandbox Code Playgroud)
输出是:
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!
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,在第二个脚本的10秒后打印所有内容.
这段代码完全按照我的预期工作(我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";
Run Code Online (Sandbox Code Playgroud)
如果它不适合你,你可能会遭受缓冲.或者,您能否为我们提供一个完整的,自包含的程序来演示您的问题?
更新:正如我上面提到的,你正在遭受缓冲.你读过我链接的文章了吗?您需要做的就是关闭STDOUT上的缓冲.
$|++;
Run Code Online (Sandbox Code Playgroud)
更新2:要清楚,您需要将代码放入test2.pl- 这是正在执行缓冲打印的程序,因此您需要关闭缓冲区.
| 归档时间: |
|
| 查看次数: |
344 次 |
| 最近记录: |