简体   繁体   中英

Dynamically capture output of system command in Perl

In my Perl code, I use a system command to run a script. I'm using Gtk2::Perl and Glade to build a 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.

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:

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).

while ( <$process_output> ) { 
   print; 
}

close ( $process_output ); 

You can 'fake' the behaviour of system via the waitpid system call:

 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() forks a new process and waits for it to terminate. Then your program continues (see 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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