在 Perl 中动态捕获系统命令的输出
Dynamically capture output of system command in Perl
在我的 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.
如有任何帮助,我们将不胜感激。
system()
做不到您想做的事。 System()
派生一个新进程 并且 等待它终止。然后你的程序继续(见manual). You could start a sub-process (executing whatever system()
did for you) and read this sub-process' stdout. You could for example get inspired here: redirecting stdin/stdout from exec'ed process to pipe in Perl
如果您尝试 'capture' system
调用的输出,那么我建议最好的方法是使用 open
并打开您的进程的文件句柄:
my $pid = open ( my $process_output, '-|', "command" );
然后您可以像读取文件句柄一样读取 $process_output
(请记住,如果没有待处理的 IO,它会阻塞)。
while ( <$process_output> ) {
print;
}
close ( $process_output );
您可以通过 waitpid
系统调用 'fake' system
的行为:
waitpid ( $pid, 0 );
这将 'block' 您的主程序,直到系统调用完成。
在我的 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.
如有任何帮助,我们将不胜感激。
system()
做不到您想做的事。 System()
派生一个新进程 并且 等待它终止。然后你的程序继续(见manual). You could start a sub-process (executing whatever system()
did for you) and read this sub-process' stdout. You could for example get inspired here: redirecting stdin/stdout from exec'ed process to pipe in Perl
如果您尝试 'capture' system
调用的输出,那么我建议最好的方法是使用 open
并打开您的进程的文件句柄:
my $pid = open ( my $process_output, '-|', "command" );
然后您可以像读取文件句柄一样读取 $process_output
(请记住,如果没有待处理的 IO,它会阻塞)。
while ( <$process_output> ) {
print;
}
close ( $process_output );
您可以通过 waitpid
系统调用 'fake' system
的行为:
waitpid ( $pid, 0 );
这将 'block' 您的主程序,直到系统调用完成。