Skip to main content

Capture stdout/stderr and optionally release when an exception occurs.

Project description

Compatibility Implementations Format Downloads

Capture stdout/stderr and optionally release when an exception occurs.

from abduct import captured, out, err

with captured(out()) as stdout:

with captured(out(), err()) as (stdout, stderr):

@captured(out(), err())


$ pip install abduct

When stdout or stderr is captured, the related sys.stdout or sys.stderr object is replaced with a StringIO object for the life of the context.


It’s often useful to capture the output of a block of code. Abduct makes this easy:

with captured(out()) as stdout:

assert stdout.getvalue() == 'hello!'

Sometimes you may want to hide the output of some code unless something goes wrong. In this case, simply specify release_on_exception=True:

with captured(out(release_on_exception=True)):
    print('Really important message!')
    if blow_up:
        raise RuntimeError()

In this case, Really important message! will be printed on stdout if the exception is raised.

If you’d like to capture the output, but still write through to stdout or stderr, use the tee=True parameter:

with captured(err(tee=True)) as stderr:

assert stderr.getvalue() == 'Error!'

In this case, Error! is captured and written to stderr at the same time.



  • Added tests for the decorator usage.


  • Feature: “Create a write-through option for output.”
  • Backwards-incompatible change: stdout and stderr methods are now out and err respectively.


  • Fixed Travis release criteria.


  • Refactored test runner.


  • Fixed README and description.


  • Travis config now defers to tox.
  • Added examples to README.


  • Actual working code. Yay!


  • Initial release.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for abduct, version 2.0.1
Filename, size File type Python version Upload date Hashes
Filename, size abduct-2.0.1-py2.py3-none-any.whl (3.4 kB) File type Wheel Python version 2.7 Upload date Hashes View
Filename, size abduct-2.0.1.tar.gz (2.9 kB) File type Source Python version None Upload date Hashes View

Supported by

Pingdom Pingdom Monitoring Google Google Object Storage and Download Analytics Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page