[英]Dynamically capture output of system command in Perl
In my Perl code, I use a system command to run a script. 在我的Perl代码中,我使用系统命令来运行脚本。 I'm using Gtk2::Perl and Glade to build a UI. 我正在使用Gtk2 :: Perl和Glade构建UI。 I need the output of the command to be captured not just to the console (which Capture::Tiny
does), but also to a TextView in my GUI. 我不仅需要将命令的输出捕获到控制台( Capture::Tiny
会Capture::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.
Any help would be greatly appreciated. 任何帮助将不胜感激。
If you're trying to 'capture' the output of a system
call, then I would suggest the best approach is to use open
and open a filehandle to your process: 如果您试图“捕获” system
调用的输出,那么我建议最好的方法是对进程使用open
和open filehandle:
my $pid = open ( my $process_output, '-|', "command" );
Then you can read $process_output
exactly as you would a file handle (bear in mind it'll block if there's no IO pending). 然后,您可以完全像处理文件一样读取$process_output
(请记住,如果没有IO挂起,它将阻塞)。
while ( <$process_output> ) {
print;
}
close ( $process_output );
You can 'fake' the behaviour of system
via the waitpid
system call: 您可以通过waitpid
系统调用来“伪造” system
的行为:
waitpid ( $pid, 0 );
This will 'block' your main program until the system call has completed. 这将“阻塞”您的主程序,直到系统调用完成。
What you want to do is not possible with system()
. 使用system()
无法实现您想做的事情。 System()
forks a new process and waits for it to terminate. System()
派生一个新进程并等待其终止。 Then your program continues (see manual ). 然后您的程序继续(请参阅手册 )。 You could start a sub-process (executing whatever system()
did for you) and read this sub-process' stdout. 您可以启动一个子流程(执行任何system()
为您执行的操作)并读取此子流程的stdout。 You could for example get inspired here: redirecting stdin/stdout from exec'ed process to pipe in Perl 例如,您可能在这里受到启发: 将stdin / stdout从执行的进程重定向到Perl中的管道
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.