#!/usr/bin/env python # coding: utf-8 # # Capturing Output With %%capture # IPython has a [cell magic](Cell Magics.ipynb), `%%capture`, which captures the stdout/stderr of a cell. With this magic you can discard these streams or store them in a variable. # In[1]: from __future__ import print_function import sys # By default, `%%capture` discards these streams. This is a simple way to suppress unwanted output. # In[2]: get_ipython().run_cell_magic('capture', '', "print('hi, stdout')\nprint('hi, stderr', file=sys.stderr)\n") # If you specify a name, then stdout/stderr will be stored in an object in your namespace. # In[3]: get_ipython().run_cell_magic('capture', 'captured', "print('hi, stdout')\nprint('hi, stderr', file=sys.stderr)\n") # In[4]: captured # Calling the object writes the output to stdout/stderr as appropriate. # In[5]: captured() # In[6]: captured.stdout # In[7]: captured.stderr # `%%capture` grabs all output types, not just stdout/stderr, so you can do plots and use IPython's display system inside `%%capture` # In[8]: get_ipython().run_line_magic('matplotlib', 'inline') import matplotlib.pyplot as plt import numpy as np # In[9]: get_ipython().run_cell_magic('capture', 'wontshutup', '\nprint("setting up X")\nx = np.linspace(0,5,1000)\nprint("step 2: constructing y-data")\ny = np.sin(x)\nprint("step 3: display info about y")\nplt.plot(x,y)\nprint("okay, I\'m done now")\n') # In[10]: wontshutup() # And you can selectively disable capturing stdout, stderr or rich display, by passing `--no-stdout`, `--no-stderr` and `--no-display` # In[11]: get_ipython().run_cell_magic('capture', 'cap --no-stderr', 'print(\'hi, stdout\')\nprint("hello, stderr", file=sys.stderr)\n') # In[12]: cap.stdout # In[13]: cap.stderr # In[14]: cap.outputs