4

I need to execute a command from my Perl script, which is going to take a while (1-2 hours). I want to be able to see the output of the command, so that my script can check everything went OK, but as it takes such a long time, I'd like the user to see the commands output while it runs, too.

What I've tried:

  • backticks - Can only get output when command is finished
  • system - Can only get output when command is finished
  • open - Almost perfect - but the commands output is buffered, meaning users don't see an update for a long time. Internet is full of suggestions to set $| = 1 but apparently this only affects input buffering and doesn't work
  • Piping to tee - Similar results to open - 'tee' only seems to print later
  • Re-directing output and Using Proc::Background and File::Tail - Almost perfect again, but can't think of an elegant way to stop the print loop

Would love to have a suggestion!


Edit: I've accepted Barmars answer. I believe it works because Expect.pm uses a pseudo-terminal. Just to others looking at this question in future, this is how I've implemented it:

my $process = Expect->spawn($command, @params) or die "Cannot spawn $command: $!\n";

while ($process->expect(undef))
{
  print $process->before();
}
7
  • 2
    Have a look at stackoverflow.com/a/214005/1331451 Commented Sep 3, 2012 at 9:08
  • Setting autoflush to a true value disables buffering for the currently selected file handle. How is that different from what you are asking for? Commented Sep 3, 2012 at 9:19
  • TLP, as I said I tried that, and it didn't seem to work. Upon researching it, I read that autoflush only affects input buffering. Commented Sep 3, 2012 at 9:22
  • 1
    The phrase it doesn't work and all its variations is next to useless without elaboration. And no, it is output buffering. There is no input buffering. Commented Sep 3, 2012 at 9:32
  • 1
    @TLP, I would add more than one up to that comment if I could. Commented Sep 11, 2012 at 13:02

1 Answer 1

2

Using Expect.pm should disable output buffering in the command.

Sign up to request clarification or add additional context in comments.

1 Comment

Seems to work beautifully and has an elegant implementation. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.