Code Cells — Recipe 0.1.0 documentation

# Code Cells

## Code, Output, Streams

An empty code cell:

Two empty lines:

    In [1]:

Leading/trailing empty lines:

    In [1]:

    # 2 empty lines before, 1 after

A simple output:

    In [2]:

    6 * 7

    Out[2]:

    42

The standard output stream:

    In [3]:

    print('Hello, world!')

    Hello, world!

Normal output + standard output

    In [4]:

    print('Hello, world!')
    6 * 7

    Hello, world!

    Out[4]:

    42

The standard error stream is highlighted and displayed just below the code cell. The standard output stream comes afterwards (with no special highlighting). Finally, the “normal” output is displayed.

    In [5]:

    import sys

    print("I'll appear on the standard error stream")
    print("I'll appear on the standard output stream")
    "I'm the 'normal' output"

    I'll appear on the standard error stream
    I'll appear on the standard output stream

    Out[5]:

    "I'm the 'normal' output"

## Cell Magics

IPython can handle code in other languages by means of cell magics:

    In [6]:

    %%bash
    for i in 1 2 3
    do
        echo $i
    done

    1
    2
    3

## Special Display Formats

See IPython example notebook.

TODO: tables? e.g. Pandas DataFrame?

    In [7]:

    from IPython.display import display

### Local Image Files

    In [8]:

    from IPython.display import Image
    i = Image(filename='images/notebook_icon.png')
    i

    ---------------------------------------------------------------------------
    IOError                                   Traceback (most recent call last)
    <ipython-input-8-cf6085be776e> in <module>()
          1 from IPython.display import Image
    ----> 2 i = Image(filename='images/notebook_icon.png')
          3 i

    /Users/chrisgemignani/.virtualenvs/recipe/lib/python2.7/site-packages/IPython/core/display.pyc in __init__(self, data, url, filename, format, embed, width, height, retina, unconfined, metadata)
       1019         self.unconfined = unconfined
       1020         self.metadata = metadata
    -> 1021         super(Image, self).__init__(data=data, url=url, filename=filename)
       1022
       1023         if retina:

    /Users/chrisgemignani/.virtualenvs/recipe/lib/python2.7/site-packages/IPython/core/display.pyc in __init__(self, data, url, filename)
        611         self.filename = None if filename is None else unicode_type(filename)
        612
    --> 613         self.reload()
        614         self._check_data()
        615

    /Users/chrisgemignani/.virtualenvs/recipe/lib/python2.7/site-packages/IPython/core/display.pyc in reload(self)
       1041         """Reload the raw data from file or URL."""
       1042         if self.embed:
    -> 1043             super(Image,self).reload()
       1044             if self.retina:
       1045                 self._retina_shape()

    /Users/chrisgemignani/.virtualenvs/recipe/lib/python2.7/site-packages/IPython/core/display.pyc in reload(self)
        629         """Reload the raw data from file or URL."""
        630         if self.filename is not None:
    --> 631             with open(self.filename, self._read_flags) as f:
        632                 self.data = f.read()
        633         elif self.url is not None:

    IOError: [Errno 2] No such file or directory: u'images/notebook_icon.png'

    In [9]:

    display(i)

    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-9-e1076fad41b4> in <module>()
    ----> 1 display(i)

    NameError: name 'i' is not defined

For some reason this doesn’t work with `Image(...)`:

    In [10]:

    from IPython.display import SVG
    SVG(filename='images/python_logo.svg')

    ---------------------------------------------------------------------------
    IOError                                   Traceback (most recent call last)
    <ipython-input-10-46af09a17792> in <module>()
          1 from IPython.display import SVG
    ----> 2 SVG(filename='images/python_logo.svg')

    /Users/chrisgemignani/.virtualenvs/recipe/lib/python2.7/site-packages/IPython/core/display.pyc in __init__(self, data, url, filename)
        611         self.filename = None if filename is None else unicode_type(filename)
        612
    --> 613         self.reload()
        614         self._check_data()
        615

    /Users/chrisgemignani/.virtualenvs/recipe/lib/python2.7/site-packages/IPython/core/display.pyc in reload(self)
        629         """Reload the raw data from file or URL."""
        630         if self.filename is not None:
    --> 631             with open(self.filename, self._read_flags) as f:
        632                 self.data = f.read()
        633         elif self.url is not None:

    IOError: [Errno 2] No such file or directory: u'images/python_logo.svg'

### Image URLs

    In [11]:

    Image(url='https://www.python.org/static/img/python-logo-large.png')

    Out[11]:

    In [12]:

    Image(url='https://www.python.org/static/img/python-logo-large.png', embed=True)

    Out[12]:

    In [13]:

    Image(url='http://jupyter.org/assets/nav_logo.svg')

    Out[13]:

    In [14]:

    Image(url='https://www.python.org/static/favicon.ico')

    Out[14]:

    In [15]:

    Image(url='http://python.org/images/python-logo.gif')

    Out[15]:

### Math

    In [16]:

    from IPython.display import Math
    eq = Math(r"\int_{-\infty}^\infty f(x) \delta(x - x_0) dx = f(x_0)")
    eq

    Out[16]:

    In [17]:

    display(eq)

    In [18]:

    %%latex
    \begin{equation}
    \int_{-\infty}^\infty f(x) \delta(x - x_0) dx = f(x_0)
    \end{equation}

### YouTube Videos

    In [19]:

    from IPython.display import YouTubeVideo
    YouTubeVideo('WAikxUGbomY')

    Out[19]:

### Arbitrary JavaScript Output (HTML only)

    In [20]:

    %%javascript

    var text = document.createTextNode("Hello, I was generated with JavaScript!");
    // Content appended to "element" will be visible in the output area:
    element.appendChild(text);

Note:

jQuery should be available, but using the readthedocs.org default theme, it’s not. See the issue on Github. Other Sphinx themes are not affected by this.

### Unsupported Output Types

If a code cell produces data with an unsupported MIME type, the Jupyter Notebook doesn’t generate any output. `nbsphinx`, however, shows a warning message.

    In [21]:

    display({
        'text/x-python': 'print("Hello, world!")',
        'text/x-haskell': 'main = putStrLn "Hello, world!"',
    }, raw=True)

Data type cannot be displayed: text/x-haskell, text/x-python

## ANSI Colors

The standard output and standard error streams may contain ANSI escape sequences to change the text and background colors.

    In [22]:

    print('BEWARE: \x1b[1;33;41mugly colors\x1b[m!', file=sys.stderr)
    print('AB\x1b[43mCD\x1b[35mEF\x1b[1mGH\x1b[4mIJ\x1b[7m'
          'KL\x1b[49mMN\x1b[39mOP\x1b[22mQR\x1b[24mST\x1b[27mUV')

      File "<ipython-input-22-03c2b4a945af>", line 1
        print('BEWARE: \x1b[1;33;41mugly colors\x1b[m!', file=sys.stderr)
                                                             ^
    SyntaxError: invalid syntax

The following code showing the 8 basic ANSI colors is based on http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html. Each of the 8 colors has an “intense” variation, which is used for bold text.

    In [23]:

    text = ' XYZ '
    formatstring = '\x1b[{}m' + text + '\x1b[m'

    print(' ' * 6 + ' ' * len(text) +
          ''.join('{:^{}}'.format(bg, len(text)) for bg in range(40, 48)))
    for fg in range(30, 38):
        for bold in False, True:
            fg_code = ('1;' if bold else '') + str(fg)
            print(' {:>4} '.format(fg_code) + formatstring.format(fg_code) +
                  ''.join(formatstring.format(fg_code + ';' + str(bg))
                          for bg in range(40, 48)))

                40   41   42   43   44   45   46   47
       30  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ
     1;30  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ
       31  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ
     1;31  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ
       32  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ
     1;32  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ
       33  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ
     1;33  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ
       34  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ
     1;34  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ
       35  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ
     1;35  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ
       36  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ
     1;36  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ
       37  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ
     1;37  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ  XYZ

ANSI also supports a set of 256 indexed colors. The following code showing all of them is based on http://bitmote.com/index.php?post/2012/11/19/Using-ANSI-Color-Codes-to-Colorize-Your-Bash-Prompt-on-Linux.

    In [24]:

    formatstring = '\x1b[38;5;{0};48;5;{0}mX\x1b[1mX\x1b[m'

    print('  + ' + ''.join('{:2}'.format(i) for i in range(36)))
    print('  0 ' + ''.join(formatstring.format(i) for i in range(16)))
    for i in range(7):
        i = i * 36 + 16
        print('{:3} '.format(i) + ''.join(formatstring.format(i + j)
                                          for j in range(36) if i + j < 256))

      +  0 1 2 3 4 5 6 7 8 91011121314151617181920212223242526272829303132333435
      0 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
     16 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
     52 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
     88 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    124 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    160 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    196 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    232 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

You can even use 24-bit RGB colors:

    In [25]:

    start = 255, 0, 0
    end = 0, 0, 255
    length = 79
    out = []

    for i in range(length):
        rgb = [start[c] + int(i * (end[c] - start[c]) / length) for c in range(3)]
        out.append('\x1b['
                   '38;2;{rgb[2]};{rgb[1]};{rgb[0]};'
                   '48;2;{rgb[0]};{rgb[1]};{rgb[2]}mX\x1b[m'.format(rgb=rgb))
    print(''.join(out))

    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX