在Perl中动态捕获系统命令的输出

时间:2015-06-30 09:04:37

标签: perl glade

在我的Perl代码中,我使用系统命令来运行脚本。我正在使用Gtk2 :: Perl和Glade来构建UI。我需要将命令的输出不仅捕获到控制台(Capture::Tiny执行),还要捕获到GUI中的TextView。

system("command");

$stdout = tee{                         #This captures the output to the console
system("command");  
};

$textbuffer->set_text($stdout);       #This does set the TextView with the captured output, but *after* the capture is over. 

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:4)

如果您尝试“捕获”system来电的输出,那么我建议最好的方法是使用open并为您的流程打开文件句柄:

my $pid = open ( my $process_output, '-|', "command" ); 

然后你可以像文件句柄那样完全阅读$process_output(请记住,如果没有IO待处理,它会阻止)。

while ( <$process_output> ) { 
   print; 
}

close ( $process_output ); 

您可以通过system系统调用“伪造”waitpid的行为:

 waitpid ( $pid, 0 ); 

这将“阻止”您的主程序,直到系统调用完成。

答案 1 :(得分:2)

system()无法实现您的目标。 System()分叉新进程等待它终止。然后你的程序继续(见manual)。你可以开始一个子流程(执行system()为你做的任何事情)并阅读这个子流程&#39;标准输出。例如,你可以从这里得到启发:redirecting stdin/stdout from exec'ed process to pipe in Perl

相关问题