Example #1
0
def split_matplotlib_cells(nb):
    """
    If a cell imports matplotlib, split the cell to keep the
    import statement separate from the code that uses matplotlib.
    This prevents a known bug in the Jupyter backend which causes
    the plot object to be represented as a string instead of a canvas
    when created in the cell where matplotlib is imported for the
    first time (https://github.com/jupyter/notebook/issues/3523).
    """
    for i in range(len(nb['cells']) - 1, -1, -1):
        cell = nb['cells'][i]
        if cell['cell_type'] == 'code' and 'matplotlib' in cell['source']:
            code = iw.protect_ipython_magics(cell['source'])
            # split cells after matplotlib imports
            mapping = iw.delimit_statements(code)
            tree = ast.parse(code)
            visitor = iw.GetMatplotlibPyplot()
            visitor.visit(tree)
            if visitor.matplotlib_first:
                code = iw.deprotect_ipython_magics(code)
                lines = code.split('\n')
                lineno_end = mapping[visitor.matplotlib_first]
                split_code = '\n'.join(lines[lineno_end:]).lstrip('\n')
                if split_code:
                    new_cell = nbformat.v4.new_code_cell(source=split_code)
                    nb['cells'].insert(i + 1, new_cell)
                lines = lines[:lineno_end]
                nb['cells'][i]['source'] = '\n'.join(lines).rstrip('\n')
 def test_ipython_magics(self):
     lines = [
         '%matplotlib inline',
         '%%matplotlib notebook',
         'import matplotlib.pyplot as plt',
         '__doc__="%matplotlib inline"',
     ]
     code = '\n'.join(lines)
     code_protected = iw.protect_ipython_magics(code)
     code_protected_ref = f'\n{code}'.replace(
         '\n%', '\n#_IPYTHON_MAGIC_%')[1:]
     self.assertEqual(code_protected, code_protected_ref)
     code_deprotected = iw.deprotect_ipython_magics(code_protected)
     self.assertEqual(code_deprotected, code)
Example #3
0
# if matplotlib is used in this script, split cell to keep the import
# statement separate and avoid a known bug in the Jupyter backend which
# causes the plot object to be represented as a string instead of a
# canvas when created in the cell where matplotlib is imported for the
# first time (https://github.com/jupyter/notebook/issues/3523)
for i in range(len(nb['cells'])):
    cell = nb['cells'][i]
    if cell['cell_type'] == 'code' and 'matplotlib' in cell['source']:
        code = iw.protect_ipython_magics(cell['source'])
        # split cells after matplotlib imports
        mapping = iw.delimit_statements(code)
        tree = ast.parse(code)
        visitor = iw.GetMatplotlibPyplot()
        visitor.visit(tree)
        if visitor.matplotlib_first:
            code = iw.deprotect_ipython_magics(code)
            lines = code.split('\n')
            lineno_end = mapping[visitor.matplotlib_first]
            split_code = '\n'.join(lines[lineno_end:]).lstrip('\n')
            if split_code:
                new_cell = nbformat.v4.new_code_cell(source=split_code)
                nb['cells'].insert(i + 1, new_cell)
            lines = lines[:lineno_end]
            nb['cells'][i]['source'] = '\n'.join(lines).rstrip('\n')
            break

# substitute global variables and disable OpenGL/Mayavi GUI
cell_separator = '\n##{}\n'.format(uuid.uuid4().hex)
src = cell_separator.join(get_code_cells(nb))
parameters = dict(x.split('=', 1) for x in new_values)
src = iw.substitute_variable_values(src, strings_as_is=True,