#!/usr/bin/env python # coding: utf-8 # # Cell Magics in IPython # IPython has a system of commands we call 'magics' that provide a mini command language that is orthogonal to the syntax of Python and is extensible by the user with new commands. Magics are meant to be typed interactively, so they use command-line conventions, such as using whitespace for separating arguments, dashes for options and other conventions typical of a command-line environment. # # Magics come in two kinds: # # * Line magics: these are commands prepended by one `%` character and whose arguments only extend to the end of the current line. # * Cell magics: these use *two* percent characters as a marker (`%%`), and they receive as argument *both* the current line where they are declared and the whole body of the cell. Note that cell magics can *only* be used as the first line in a cell, and as a general principle they can't be 'stacked' (i.e. you can only use one cell magic per cell). A few of them, because of how they operate, can be stacked, but that is something you will discover on a case by case basis. # # The `%lsmagic` magic is used to list all available magics, and it will show both line and cell magics currently defined: # In[1]: get_ipython().run_line_magic('lsmagic', '') # Since in the introductory section we already covered the most frequently used line magics, we will focus here on the cell magics, which offer a great amount of power. # # Let's load matplotlib and numpy so we can use numerics/plotting at will later on. # In[2]: get_ipython().run_line_magic('matplotlib', 'inline') import numpy as np import matplotlib.pyplot as plt # ## Some simple cell magics # Timing the execution of code; the 'timeit' magic exists both in line and cell form: # In[3]: get_ipython().run_line_magic('timeit', 'np.linalg.eigvals(np.random.rand(100,100))') # In[4]: get_ipython().run_cell_magic('timeit', 'a = np.random.rand(100, 100)', 'np.linalg.eigvals(a)\n') # The `%%capture` magic can be used to capture the stdout/err of any block of python code, either to discard it (if it's noise to you) or to store it in a variable for later use: # In[5]: get_ipython().run_cell_magic('capture', 'capt', "from __future__ import print_function\nimport sys\nprint('Hello stdout')\nprint('and stderr', file=sys.stderr)\n") # In[6]: capt.stdout, capt.stderr # In[7]: capt.show() # The `%%writefile` magic is a very useful tool that writes the cell contents as a named file: # In[8]: get_ipython().run_cell_magic('writefile', 'foo.py', "print('Hello world')\n") # In[9]: get_ipython().run_line_magic('run', 'foo') # ## Magics for running code under other interpreters # IPython has a `%%script` cell magic, which lets you run a cell in # a subprocess of any interpreter on your system, such as: bash, ruby, perl, zsh, R, etc. # # It can even be a script of your own, which expects input on stdin. # To use it, simply pass a path or shell command to the program you want to run on the `%%script` line, # and the rest of the cell will be run by that script, and stdout/err from the subprocess are captured and displayed. # In[10]: get_ipython().run_cell_magic('script', 'python2', "import sys\nprint 'hello from Python %s' % sys.version\n") # In[11]: get_ipython().run_cell_magic('script', 'python3', "import sys\nprint('hello from Python: %s' % sys.version)\n") # IPython also creates aliases for a few common interpreters, such as bash, ruby, perl, etc. # # These are all equivalent to `%%script ` # In[12]: get_ipython().run_cell_magic('ruby', '', 'puts "Hello from Ruby #{RUBY_VERSION}"\n') # In[13]: get_ipython().run_cell_magic('bash', '', 'echo "hello from $BASH"\n') # ## Capturing output # You can also capture stdout/err from these subprocesses into Python variables, instead of letting them go directly to stdout/err # In[14]: get_ipython().run_cell_magic('bash', '', 'echo "hi, stdout"\necho "hello, stderr" >&2\n') # In[15]: get_ipython().run_cell_magic('bash', '--out output --err error', 'echo "hi, stdout"\necho "hello, stderr" >&2\n') # In[16]: print(error) print(output) # ## Background Scripts # These scripts can be run in the background, by adding the `--bg` flag. # # When you do this, output is discarded unless you use the `--out/err` # flags to store output as above. # In[17]: get_ipython().run_cell_magic('ruby', '--bg --out ruby_lines', 'for n in 1...10\n sleep 1\n puts "line #{n}"\n STDOUT.flush\nend\n') # When you do store output of a background thread, these are the stdout/err *pipes*, # rather than the text of the output. # In[18]: ruby_lines # In[19]: print(ruby_lines.read().decode('utf8'))