7

I need to call some shell commands from perl. Those commands take quite some time to finish so I'd like to see their output while waiting for completion.

The system function does not give me any output until it is completed.

The exec function gives output; however, it exits the perl script from that point, which is not what I wanted.

I am on Windows. Is there a way to accomplish this?

cuteCAT
  • 2,251
  • 4
  • 25
  • 30

1 Answers1

17

Backticks, or the qx command, run a command in a separate process and returns the output:

print `$command`;
print qx($command);

If you wish to see intermediate output, use open to create a handle to the command's output stream and read from it.

open my $cmd_fh, "$command |";   # <---  | at end means to make command 
                                 #         output available to the handle
while (<$cmd_fh>) {
    print "A line of output from the command is: $_";
}
close $cmd_fh;
mob
  • 117,087
  • 18
  • 149
  • 283
  • 1
    @Nathan - Probably, but it's even more important for the external command to have good buffering behavior -- either not buffering its output, or producing output quickly enough that buffering doesn't matter. – mob Dec 14 '10 at 20:35
  • 4
    ++ for backticks AND piped open - The only nitpick I have is the lack of mention of the 3+ args version of the technique, which should be somewhat safer: open my $cmd_fh, '-|', $command; Also, link: http://perldoc.perl.org/perlopentut.html#Pipe-Opens – Hugmeir Dec 14 '10 at 20:54
  • This solution (also documented here: https://www.shlomifish.org/lecture/Perl/Newbies/lecture4/processes/opens.html) didn't seem to work for me calling another script --> Not sure if the script I'm calling isn't printing to the right output stream? (Thought it just looks like command line when I run it directly) – fobbymaster Dec 19 '22 at 17:19
  • @fobbymaster If it is a long-running script, you may be [suffering from buffering](https://perl.plover.com/FAQs/Buffering.html) – mob Dec 19 '22 at 19:49