Capture::Tiny - Capture STDOUT and STDERR from Perl, XS or external programs
version 0.13
use Capture::Tiny ':all'; ($stdout, $stderr, @result) = capture { # your code here }; $stdout = capture_stdout { ... }; $stderr = capture_stderr { ... }; $merged = capture_merged { ... }; ($stdout, $stderr) = tee { # your code here }; $stdout = tee_stdout { ... }; $stderr = tee_stderr { ... }; $merged = tee_merged { ... };
Capture::Tiny provides a simple, portable way to capture almost anything sent to STDOUT or STDERR, regardless of whether it comes from Perl, from XS code or from an external program. Optionally, output can be teed so that it is captured while being passed through to the original handles. Yes, it even works on Windows (usually). Stop guessing which of a dozen capturing modules to use in any particular situation and just use this one.
The following functions are available. None are exported by default.
($stdout, $stderr, @result) = capture \&code; $stdout = capture \&code;
The capture function takes a code reference and returns what is sent to STDOUT and STDERR as well as any return values from the code reference. In scalar context, it returns only STDOUT. If no output was received for a handle, it returns an empty string for that handle. Regardless of calling context, all output is captured -- nothing is passed to the existing handles.
capture
It is prototyped to take a subroutine reference as an argument. Thus, it can be called in block form:
($stdout, $stderr) = capture { # your code here ... };
Note that the coderef is evaluated in list context. If you wish to force scalar context on the return value, you must use the scalar keyword.
scalar
($stdout, $stderr, $count) = capture { my @list = qw/one two three/; return scalar @list; # $count will be 3 };
Captures are normally done internally to an anonymous filehandle. To capture via a named file (e.g. to externally monitor a long-running capture), provide custom filehandles as a trailing list of option pairs:
my $out_fh = IO::File->new("out.txt", "w+"); my $err_fh = IO::File->new("out.txt", "w+"); capture { ... } stdout => $out_fh, stderr => $err_fh;
The filehandles must be read/write and seekable and should be empty. Modifying the files externally during a capture operation will give unpredictable results. Existing IO layers on them may be changed by the capture.
($stdout, @result) = capture_stdout \&code; $stdout = capture_stdout \&code;
The capture_stdout function works just like capture except only STDOUT is captured. STDERR is not captured.
capture_stdout
($stderr, @result) = capture_stderr \&code; $stderr = capture_stderr \&code;
The capture_stderr function works just like capture except only STDERR is captured. STDOUT is not captured.
capture_stderr
($merged, @result) = capture_merged \&code; $merged = capture_merged \&code;
The capture_merged function works just like capture except STDOUT and STDERR are merged. (Technically, STDERR is redirected to STDOUT before executing the function.)
capture_merged
Caution: STDOUT and STDERR output in the merged result are not guaranteed to be properly ordered due to buffering.
($stdout, $stderr, @result) = tee \&code; $stdout = tee \&code;
The tee function works just like capture, except that output is captured as well as passed on to the original STDOUT and STDERR.
tee
($stdout, @result) = tee_stdout \&code; $stdout = tee_stdout \&code;
The tee_stdout function works just like tee except only STDOUT is teed. STDERR is not teed (output goes to STDERR as usual).
tee_stdout
($stderr, @result) = tee_stderr \&code; $stderr = tee_stderr \&code;
The tee_stderr function works just like tee except only STDERR is teed. STDOUT is not teed (output goes to STDOUT as usual).
tee_stderr
($merged, @result) = tee_merged \&code; $merged = tee_merged \&code;
The tee_merged function works just like capture_merged except that output is captured as well as passed on to STDOUT.
tee_merged
Portability is a goal, not a guarantee. tee requires fork, except on Windows where system(1, @cmd) is used instead. Not tested on any particularly esoteric platforms yet.
system(1, @cmd)
Capture::Tiny does it's best to preserve PerlIO layers such as ':utf8' or ':crlf' when capturing. Layers should be applied to STDOUT or STDERR before the call to capture or tee. This may not work for tied handles (see below).
Generally speaking, you should do little or no manipulation of the standard IO handles prior to using Capture::Tiny. In particular, closing, reopening, localizing or tying standard handles prior to capture may cause a variety of unexpected, undesireable and/or unreliable behaviors, as described below. Capture::Tiny does its best to compensate for these situations, but the results may not be what you desire.
Closed filehandles
Capture::Tiny will work even if STDIN, STDOUT or STDERR have been previously closed. However, since they will be reopened to capture or tee output, any code within the captured block that depends on finding them closed will, of course, not find them to be closed. If they started closed, Capture::Tiny will reclose them again when the capture block finishes.
Note that this reopening will happen even for STDIN or a handle not being captured to ensure that the filehandle used for capture is not opened to file descriptor 0, as this causes problems on various platforms.
Localized filehandles
If code localizes any of Perl's standard handles before capturing, the capture will affect the localized handles and not the original ones. External system calls are not affected by localizing a handle in Perl and will continue to send output to the original handles (which will thus not be captured).
Scalar filehandles
If STDOUT or STDERR are reopened to scalar filehandles prior to the call to capture or tee, then Capture::Tiny will override the output handle for the duration of the capture or tee call and then send captured output to the output handle after the capture is complete. (Requires Perl 5.8)
Capture::Tiny attempts to preserve the semantics of STDIN opened to a scalar reference.
Tied handles
If STDOUT or STDERR are tied prior to the call to capture or tee, then Capture::Tiny will attempt to override the tie for the duration of the capture or tee call and then send captured output to the tied handle after the capture is complete. (Requires Perl 5.8)
Capture::Tiny may not succeed resending utf8 encoded data to a tied STDOUT or STDERR handle. Characters may appear as bytes. If the tied handle is based on Tie::StdHandle, then Capture::Tiny will attempt to determine appropriate layers like :utf8 from the underlying handle and do the right thing.
:utf8
Capture::Tiny attempts to preserve the semantics of tied STDIN, but capturing or teeing when STDIN is tied is currently broken on Windows.
Attempting to modify STDIN, STDOUT or STDERR during capture or tee is almost certainly going to cause problems. Don't do that.
It's just too buggy when it comes to layers and UTF8.
Capture::Tiny uses subprocesses for tee. By default, Capture::Tiny will timeout with an error if the subprocesses are not ready to receive data within 30 seconds (or whatever is the value of $Capture::Tiny::TIMEOUT). An alternate timeout may be specified by setting the PERL_CAPTURE_TINY_TIMEOUT environment variable. Setting it to zero will disable timeouts.
$Capture::Tiny::TIMEOUT
PERL_CAPTURE_TINY_TIMEOUT
Please report any bugs or feature requests using the CPAN Request Tracker. Bugs can be submitted through the web interface at http://rt.cpan.org/Dist/Display.html?Queue=Capture-Tiny
When submitting a bug or request, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature.
This module was, inspired by IO::CaptureOutput, which provides similar functionality without the ability to tee output and with more complicated code and API. IO::CaptureOutput does not handle layers or most of the unusual cases described in the "Limitations" section and I no longer recommend it.
There are many other CPAN modules that provide some sort of output capture, albeit with various limitations that make them appropriate only in particular circumstances. I'm probably missing some. The long list is provided to show why I felt Capture::Tiny was necessary.
IO::Capture
IO::Capture::Extended
IO::CaptureOutput
IPC::Capture
IPC::Cmd
IPC::Open2
IPC::Open3
IPC::Open3::Simple
IPC::Open3::Utils
IPC::Run
IPC::Run::SafeHandles
IPC::Run::Simple
IPC::Run3
IPC::System::Simple
Tee
IO::Tee
File::Tee
Filter::Handle
Tie::STDERR
Tie::STDOUT
Test::Output
Please report any bugs or feature requests by email to bug-capture-tiny at rt.cpan.org, or through the web interface at http://rt.cpan.org/Public/Dist/Display.html?Name=Capture-Tiny. You will be automatically notified of any progress on the request by the system.
bug-capture-tiny at rt.cpan.org
This is open source software. The code repository is available for public review and contribution under the terms of the license.
https://github.com/dagolden/capture-tiny
git clone https://github.com/dagolden/capture-tiny.git
David Golden <dagolden@cpan.org>
This software is Copyright (c) 2009 by David Golden.
This is free software, licensed under:
The Apache License, Version 2.0, January 2004
To install Capture::Tiny, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Capture::Tiny
CPAN shell
perl -MCPAN -e shell install Capture::Tiny
For more information on module installation, please visit the detailed CPAN module installation guide.