繁体   English   中英

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

[英]Dynamically capture output of system command in Perl

在我的Perl代码中,我使用系统命令来运行脚本。 我正在使用Gtk2 :: Perl和Glade构建UI。 我不仅需要将命令的输出捕获到控制台( Capture::TinyCapture::Tiny ),还需要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. 

任何帮助将不胜感激。

如果您试图“捕获” system调用的输出,那么我建议最好的方法是对进程使用open和open filehandle:

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

然后,您可以完全像处理文件一样读取$process_output (请记住,如果没有IO挂起,它将阻塞)。

while ( <$process_output> ) { 
   print; 
}

close ( $process_output ); 

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

 waitpid ( $pid, 0 ); 

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

使用system()无法实现您想做的事情。 System()派生一个新进程等待其终止。 然后您的程序继续(请参阅手册 )。 您可以启动一个子流程(执行任何system()为您执行的操作)并读取此子流程的stdout。 例如,您可能在这里受到启发: 将stdin / stdout从执行的进程重定向到Perl中的管道

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM