in reply to Capturing STDOUT and STDERR of system command, with pure perl?

the usual solution would be

I'm a bit surprised that nobody called you on rejecting the obvious solution by simple fiat. Why is qx($command 2>&1) unacceptable?

If you run into problems with IPC::Open2, the most portable solution is to redirect your own STDOUT and STDERR to file(s) before using system. If you end up wanting to capture both STDOUT and STDERR but separately, then sending at least one of them to a file is much better than trying to get Perl to drain two file handles (which can easily result in deadlock).

If you need to restore your original STDOUT and STDERR after the command's output has been gathered, then use the example code found in open's documentation for saving and then restoring them.

- tye        

  • Comment on Re: Capturing STDOUT and STDERR of system command, with pure perl? (files)
  • Download Code

Replies are listed 'Best First'.
Re^2: Capturing STDOUT and STDERR of system command, with pure perl? (files)
by EvanK (Chaplain) on Aug 24, 2007 at 17:59 UTC
    It's a wierd caveat, I know, but the command I'm executing could contain anything, including its own file descriptors.
    # command that redirects STDERR to file $command = 'myapp --flag=somearg 2>>/var/log/myapp.err';
    In such a case, if I just add new descriptors to the command, the original descriptor is apparently ignored, and the new one is used instead (on OSX anyway; YMMV).
    # NOTHING is written to the original .err file # instead, STDERR is sent to STDOUT qx($command 2>&1)
    So I needed a way to execute the command unaltered, then catch the output. I respect the constructive criticism though.

    At any rate, xdg's suggestion works well, and I may end up taking your other advice and temporarily redirect the script's stdout/err to scalars just to avoid the girth of one more dependacy :)

    __________
    Systems development is like banging your head against a wall...
    It's usually very painful, but if you're persistent, you'll get through it.