[英]Dynamically capture output of system command in Perl
在我的Perl代碼中,我使用系統命令來運行腳本。 我正在使用Gtk2 :: Perl和Glade構建UI。 我不僅需要將命令的輸出捕獲到控制台( 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.
任何幫助將不勝感激。
如果您試圖“捕獲” 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.