Example #1
0
    def notebook(self, s):
        """Export and convert yap_ipython notebooks.

        This function can export the current yap_ipython history to a notebook file.
        For example, to export the history to "foo.ipynb" do "%notebook foo.ipynb".

        The -e or --export flag is deprecated in yap_ipython 5.2, and will be
        removed in the future.
        """
        args = magic_arguments.parse_argstring(self.notebook, s)

        from nbformat import write, v4

        cells = []
        hist = list(self.shell.history_manager.get_range())
        if(len(hist)<=1):
            raise ValueError('History is empty, cannot export')
        for session, execution_count, source in hist[:-1]:
            cells.append(v4.new_code_cell(
                execution_count=execution_count,
                source=source
            ))
        nb = v4.new_notebook(cells=cells)
        with io.open(args.filename, 'w', encoding='utf-8') as f:
            write(nb, f, version=4)
Example #2
0
    def matplotlib(self, line=''):
        """Set up matplotlib to work interactively.
        
        This function lets you activate matplotlib interactive support
        at any point during an yap_ipython session. It does not import anything
        into the interactive namespace.
        
        If you are using the inline matplotlib backend in the yap_ipython Notebook
        you can set which figure formats are enabled using the following::
        
            In [1]: from yap_ipython.display import set_matplotlib_formats
            
            In [2]: set_matplotlib_formats('pdf', 'svg')

        The default for inline figures sets `bbox_inches` to 'tight'. This can
        cause discrepancies between the displayed image and the identical
        image created using `savefig`. This behavior can be disabled using the
        `%config` magic::
            
            In [3]: %config InlineBackend.print_figure_kwargs = {'bbox_inches':None}

        In addition, see the docstring of
        `yap_ipython.display.set_matplotlib_formats` and
        `yap_ipython.display.set_matplotlib_close` for more information on
        changing additional behaviors of the inline backend.

        Examples
        --------
        To enable the inline backend for usage with the yap_ipython Notebook::
        
            In [1]: %matplotlib inline

        In this case, where the matplotlib default is TkAgg::

            In [2]: %matplotlib
            Using matplotlib backend: TkAgg

        But you can explicitly request a different GUI backend::

            In [3]: %matplotlib qt

        You can list the available backends using the -l/--list option::

           In [4]: %matplotlib --list
           Available matplotlib backends: ['osx', 'qt4', 'qt5', 'gtk3', 'notebook', 'wx', 'qt', 'nbagg',
           'gtk', 'tk', 'inline']
        """
        args = magic_arguments.parse_argstring(self.matplotlib, line)
        if args.list:
            backends_list = list(backends.keys())
            print("Available matplotlib backends: %s" % backends_list)
        else:
            gui, backend = self.shell.enable_matplotlib(args.gui)
            self._show_matplotlib_backend(args.gui, backend)
Example #3
0
    def matplotlib(self, line=''):
        """Set up matplotlib to work interactively.
        
        This function lets you activate matplotlib interactive support
        at any point during an yap_ipython session. It does not import anything
        into the interactive namespace.
        
        If you are using the inline matplotlib backend in the yap_ipython Notebook
        you can set which figure formats are enabled using the following::
        
            In [1]: from yap_ipython.display import set_matplotlib_formats
            
            In [2]: set_matplotlib_formats('pdf', 'svg')

        The default for inline figures sets `bbox_inches` to 'tight'. This can
        cause discrepancies between the displayed image and the identical
        image created using `savefig`. This behavior can be disabled using the
        `%config` magic::
            
            In [3]: %config InlineBackend.print_figure_kwargs = {'bbox_inches':None}

        In addition, see the docstring of
        `yap_ipython.display.set_matplotlib_formats` and
        `yap_ipython.display.set_matplotlib_close` for more information on
        changing additional behaviors of the inline backend.

        Examples
        --------
        To enable the inline backend for usage with the yap_ipython Notebook::
        
            In [1]: %matplotlib inline

        In this case, where the matplotlib default is TkAgg::

            In [2]: %matplotlib
            Using matplotlib backend: TkAgg

        But you can explicitly request a different GUI backend::

            In [3]: %matplotlib qt

        You can list the available backends using the -l/--list option::

           In [4]: %matplotlib --list
           Available matplotlib backends: ['osx', 'qt4', 'qt5', 'gtk3', 'notebook', 'wx', 'qt', 'nbagg',
           'gtk', 'tk', 'inline']
        """
        args = magic_arguments.parse_argstring(self.matplotlib, line)
        if args.list:
            backends_list = list(backends.keys())
            print("Available matplotlib backends: %s" % backends_list)
        else:
            gui, backend = self.shell.enable_matplotlib(args.gui)
            self._show_matplotlib_backend(args.gui, backend)
Example #4
0
    def pylab(self, line=''):
        """Load numpy and matplotlib to work interactively.

        This function lets you activate pylab (matplotlib, numpy and
        interactive support) at any point during an yap_ipython session.
        
        %pylab makes the following imports::
        
            import numpy
            import matplotlib
            from matplotlib import pylab, mlab, pyplot
            np = numpy
            plt = pyplot
            
            from yap_ipython.display import display
            from yap_ipython.core.pylabtools import figsize, getfigs
            
            from pylab import *
            from numpy import *

        If you pass `--no-import-all`, the last two `*` imports will be excluded.
        
        See the %matplotlib magic for more details about activating matplotlib
        without affecting the interactive namespace.
        """
        args = magic_arguments.parse_argstring(self.pylab, line)
        if args.no_import_all is None:
            # get default from Application
            if Application.initialized():
                app = Application.instance()
                try:
                    import_all = app.pylab_import_all
                except AttributeError:
                    import_all = True
            else:
                # nothing specified, no app - default True
                import_all = True
        else:
            # invert no-import flag
            import_all = not args.no_import_all

        gui, backend, clobbered = self.shell.enable_pylab(
            args.gui, import_all=import_all)
        self._show_matplotlib_backend(args.gui, backend)
        print("Populating the interactive namespace from numpy and matplotlib")
        if clobbered:
            warn("pylab import has clobbered these variables: %s" % clobbered +
                 "\n`%matplotlib` prevents importing * from pylab and numpy")
Example #5
0
    def pylab(self, line=''):
        """Load numpy and matplotlib to work interactively.

        This function lets you activate pylab (matplotlib, numpy and
        interactive support) at any point during an yap_ipython session.
        
        %pylab makes the following imports::
        
            import numpy
            import matplotlib
            from matplotlib import pylab, mlab, pyplot
            np = numpy
            plt = pyplot
            
            from yap_ipython.display import display
            from yap_ipython.core.pylabtools import figsize, getfigs
            
            from pylab import *
            from numpy import *

        If you pass `--no-import-all`, the last two `*` imports will be excluded.
        
        See the %matplotlib magic for more details about activating matplotlib
        without affecting the interactive namespace.
        """
        args = magic_arguments.parse_argstring(self.pylab, line)
        if args.no_import_all is None:
            # get default from Application
            if Application.initialized():
                app = Application.instance()
                try:
                    import_all = app.pylab_import_all
                except AttributeError:
                    import_all = True
            else:
                # nothing specified, no app - default True
                import_all = True
        else:
            # invert no-import flag
            import_all = not args.no_import_all

        gui, backend, clobbered = self.shell.enable_pylab(args.gui, import_all=import_all)
        self._show_matplotlib_backend(args.gui, backend)
        print ("Populating the interactive namespace from numpy and matplotlib")
        if clobbered:
            warn("pylab import has clobbered these variables: %s"  % clobbered +
            "\n`%matplotlib` prevents importing * from pylab and numpy"
            )
Example #6
0
    def writefile(self, line, cell):
        """Write the contents of the cell to a file.
        
        The file will be overwritten unless the -a (--append) flag is specified.
        """
        args = magic_arguments.parse_argstring(self.writefile, line)
        filename = os.path.expanduser(args.filename)

        if os.path.exists(filename):
            if args.append:
                print("Appending to %s" % filename)
            else:
                print("Overwriting %s" % filename)
        else:
            print("Writing %s" % filename)
        
        mode = 'a' if args.append else 'w'
        with io.open(filename, mode, encoding='utf-8') as f:
            f.write(cell)
Example #7
0
    def notebook(self, s):
        """Export and convert yap_ipython notebooks.

        This function can export the current yap_ipython history to a notebook file.
        For example, to export the history to "foo.ipynb" do "%notebook foo.ipynb".

        The -e or --export flag is deprecated in yap_ipython 5.2, and will be
        removed in the future.
        """
        args = magic_arguments.parse_argstring(self.notebook, s)

        from nbformat import write, v4

        cells = []
        hist = list(self.shell.history_manager.get_range())
        if (len(hist) <= 1):
            raise ValueError('History is empty, cannot export')
        for session, execution_count, source in hist[:-1]:
            cells.append(
                v4.new_code_cell(execution_count=execution_count,
                                 source=source))
        nb = v4.new_notebook(cells=cells)
        with io.open(args.filename, 'w', encoding='utf-8') as f:
            write(nb, f, version=4)
Example #8
0
    def history(self, parameter_s=''):
        """Print input history (_i<n> variables), with most recent last.

        By default, input history is printed without line numbers so it can be
        directly pasted into an editor. Use -n to show them.

        By default, all input history from the current session is displayed.
        Ranges of history can be indicated using the syntax:
        
        ``4``
            Line 4, current session
        ``4-6``
            Lines 4-6, current session
        ``243/1-5``
            Lines 1-5, session 243
        ``~2/7``
            Line 7, session 2 before current
        ``~8/1-~6/5``
            From the first line of 8 sessions ago, to the fifth line of 6
            sessions ago.
        
        Multiple ranges can be entered, separated by spaces

        The same syntax is used by %macro, %save, %edit, %rerun

        Examples
        --------
        ::

          In [6]: %history -n 4-6
          4:a = 12
          5:print a**2
          6:%history -n 4-6

        """

        args = parse_argstring(self.history, parameter_s)

        # For brevity
        history_manager = self.shell.history_manager

        def _format_lineno(session, line):
            """Helper function to format line numbers properly."""
            if session in (0, history_manager.session_number):
                return str(line)
            return "%s/%s" % (session, line)

        # Check if output to specific file was requested.
        outfname = args.filename
        if not outfname:
            outfile = sys.stdout  # default
            # We don't want to close stdout at the end!
            close_at_end = False
        else:
            if os.path.exists(outfname):
                try:
                    ans = io.ask_yes_no("File %r exists. Overwrite?" %
                                        outfname)
                except StdinNotImplementedError:
                    ans = True
                if not ans:
                    print('Aborting.')
                    return
                print("Overwriting file.")
            outfile = io_open(outfname, 'w', encoding='utf-8')
            close_at_end = True

        print_nums = args.print_nums
        get_output = args.get_output
        pyprompts = args.pyprompts
        raw = args.raw

        pattern = None
        limit = None if args.limit is _unspecified else args.limit

        if args.pattern is not None:
            if args.pattern:
                pattern = "*" + " ".join(args.pattern) + "*"
            else:
                pattern = "*"
            hist = history_manager.search(pattern,
                                          raw=raw,
                                          output=get_output,
                                          n=limit,
                                          unique=args.unique)
            print_nums = True
        elif args.limit is not _unspecified:
            n = 10 if limit is None else limit
            hist = history_manager.get_tail(n, raw=raw, output=get_output)
        else:
            if args.range:  # Get history by ranges
                hist = history_manager.get_range_by_str(
                    " ".join(args.range), raw, get_output)
            else:  # Just get history for the current session
                hist = history_manager.get_range(raw=raw, output=get_output)

        # We could be displaying the entire history, so let's not try to pull
        # it into a list in memory. Anything that needs more space will just
        # misalign.
        width = 4

        for session, lineno, inline in hist:
            # Print user history with tabs expanded to 4 spaces.  The GUI
            # clients use hard tabs for easier usability in auto-indented code,
            # but we want to produce PEP-8 compliant history for safe pasting
            # into an editor.
            if get_output:
                inline, output = inline
            inline = inline.expandtabs(4).rstrip()

            multiline = "\n" in inline
            line_sep = '\n' if multiline else ' '
            if print_nums:
                print(u'%s:%s' %
                      (_format_lineno(session, lineno).rjust(width), line_sep),
                      file=outfile,
                      end=u'')
            if pyprompts:
                print(u">>> ", end=u"", file=outfile)
                if multiline:
                    inline = "\n... ".join(inline.splitlines()) + "\n..."
            print(inline, file=outfile)
            if get_output and output:
                print(output, file=outfile)

        if close_at_end:
            outfile.close()
Example #9
0
    def alias_magic(self, line=''):
        """Create an alias for an existing line or cell magic.

        Examples
        --------
        ::

          In [1]: %alias_magic t timeit
          Created `%t` as an alias for `%timeit`.
          Created `%%t` as an alias for `%%timeit`.

          In [2]: %t -n1 pass
          1 loops, best of 3: 954 ns per loop

          In [3]: %%t -n1
             ...: pass
             ...:
          1 loops, best of 3: 954 ns per loop

          In [4]: %alias_magic --cell whereami pwd
          UsageError: Cell magic function `%%pwd` not found.
          In [5]: %alias_magic --line whereami pwd
          Created `%whereami` as an alias for `%pwd`.

          In [6]: %whereami
          Out[6]: u'/home/testuser'
          
          In [7]: %alias_magic h history -p "-l 30" --line
          Created `%h` as an alias for `%history -l 30`.
        """

        args = magic_arguments.parse_argstring(self.alias_magic, line)
        shell = self.shell
        mman = self.shell.magics_manager
        escs = ''.join(magic_escapes.values())

        target = args.target.lstrip(escs)
        name = args.name.lstrip(escs)

        params = args.params
        if (params and ((params.startswith('"') and params.endswith('"')) or
                        (params.startswith("'") and params.endswith("'")))):
            params = params[1:-1]

        # Find the requested magics.
        m_line = shell.find_magic(target, 'line')
        m_cell = shell.find_magic(target, 'cell')
        if args.line and m_line is None:
            raise UsageError('Line magic function `%s%s` not found.' %
                             (magic_escapes['line'], target))
        if args.cell and m_cell is None:
            raise UsageError('Cell magic function `%s%s` not found.' %
                             (magic_escapes['cell'], target))

        # If --line and --cell are not specified, default to the ones
        # that are available.
        if not args.line and not args.cell:
            if not m_line and not m_cell:
                raise UsageError(
                    'No line or cell magic with name `%s` found.' % target)
            args.line = bool(m_line)
            args.cell = bool(m_cell)

        params_str = "" if params is None else " " + params

        if args.line:
            mman.register_alias(name, target, 'line', params)
            print('Created `%s%s` as an alias for `%s%s%s`.' %
                  (magic_escapes['line'], name, magic_escapes['line'], target,
                   params_str))

        if args.cell:
            mman.register_alias(name, target, 'cell', params)
            print('Created `%s%s` as an alias for `%s%s%s`.' %
                  (magic_escapes['cell'], name, magic_escapes['cell'], target,
                   params_str))
Example #10
0
def foo(self, args):
    """ A docstring.
    """
    return parse_argstring(foo, args)
Example #11
0
def magic_magic_foo(self, args):
    """ A docstring.
    """
    return parse_argstring(magic_magic_foo, args)
Example #12
0
    def history(self, parameter_s = ''):
        """Print input history (_i<n> variables), with most recent last.

        By default, input history is printed without line numbers so it can be
        directly pasted into an editor. Use -n to show them.

        By default, all input history from the current session is displayed.
        Ranges of history can be indicated using the syntax:
        
        ``4``
            Line 4, current session
        ``4-6``
            Lines 4-6, current session
        ``243/1-5``
            Lines 1-5, session 243
        ``~2/7``
            Line 7, session 2 before current
        ``~8/1-~6/5``
            From the first line of 8 sessions ago, to the fifth line of 6
            sessions ago.
        
        Multiple ranges can be entered, separated by spaces

        The same syntax is used by %macro, %save, %edit, %rerun

        Examples
        --------
        ::

          In [6]: %history -n 4-6
          4:a = 12
          5:print a**2
          6:%history -n 4-6

        """

        args = parse_argstring(self.history, parameter_s)

        # For brevity
        history_manager = self.shell.history_manager

        def _format_lineno(session, line):
            """Helper function to format line numbers properly."""
            if session in (0, history_manager.session_number):
                return str(line)
            return "%s/%s" % (session, line)

        # Check if output to specific file was requested.
        outfname = args.filename
        if not outfname:
            outfile = sys.stdout  # default
            # We don't want to close stdout at the end!
            close_at_end = False
        else:
            if os.path.exists(outfname):
                try:
                    ans = io.ask_yes_no("File %r exists. Overwrite?" % outfname)
                except StdinNotImplementedError:
                    ans = True
                if not ans:
                    print('Aborting.')
                    return
                print("Overwriting file.")
            outfile = io_open(outfname, 'w', encoding='utf-8')
            close_at_end = True

        print_nums = args.print_nums
        get_output = args.get_output
        pyprompts = args.pyprompts
        raw = args.raw

        pattern = None
        limit = None if args.limit is _unspecified else args.limit

        if args.pattern is not None:
            if args.pattern:
                pattern = "*" + " ".join(args.pattern) + "*"
            else:
                pattern = "*"
            hist = history_manager.search(pattern, raw=raw, output=get_output,
                                          n=limit, unique=args.unique)
            print_nums = True
        elif args.limit is not _unspecified:
            n = 10 if limit is None else limit
            hist = history_manager.get_tail(n, raw=raw, output=get_output)
        else:
            if args.range:      # Get history by ranges
                hist = history_manager.get_range_by_str(" ".join(args.range),
                                                        raw, get_output)
            else:               # Just get history for the current session
                hist = history_manager.get_range(raw=raw, output=get_output)

        # We could be displaying the entire history, so let's not try to pull
        # it into a list in memory. Anything that needs more space will just
        # misalign.
        width = 4

        for session, lineno, inline in hist:
            # Print user history with tabs expanded to 4 spaces.  The GUI
            # clients use hard tabs for easier usability in auto-indented code,
            # but we want to produce PEP-8 compliant history for safe pasting
            # into an editor.
            if get_output:
                inline, output = inline
            inline = inline.expandtabs(4).rstrip()

            multiline = "\n" in inline
            line_sep = '\n' if multiline else ' '
            if print_nums:
                print(u'%s:%s' % (_format_lineno(session, lineno).rjust(width),
                        line_sep),  file=outfile, end=u'')
            if pyprompts:
                print(u">>> ", end=u"", file=outfile)
                if multiline:
                    inline = "\n... ".join(inline.splitlines()) + "\n..."
            print(inline, file=outfile)
            if get_output and output:
                print(output, file=outfile)

        if close_at_end:
            outfile.close()
Example #13
0
    def alias_magic(self, line=''):
        """Create an alias for an existing line or cell magic.

        Examples
        --------
        ::

          In [1]: %alias_magic t timeit
          Created `%t` as an alias for `%timeit`.
          Created `%%t` as an alias for `%%timeit`.

          In [2]: %t -n1 pass
          1 loops, best of 3: 954 ns per loop

          In [3]: %%t -n1
             ...: pass
             ...:
          1 loops, best of 3: 954 ns per loop

          In [4]: %alias_magic --cell whereami pwd
          UsageError: Cell magic function `%%pwd` not found.
          In [5]: %alias_magic --line whereami pwd
          Created `%whereami` as an alias for `%pwd`.

          In [6]: %whereami
          Out[6]: u'/home/testuser'
          
          In [7]: %alias_magic h history -p "-l 30" --line
          Created `%h` as an alias for `%history -l 30`.
        """

        args = magic_arguments.parse_argstring(self.alias_magic, line)
        shell = self.shell
        mman = self.shell.magics_manager
        escs = ''.join(magic_escapes.values())

        target = args.target.lstrip(escs)
        name = args.name.lstrip(escs)

        params = args.params
        if (params and
                ((params.startswith('"') and params.endswith('"'))
                or (params.startswith("'") and params.endswith("'")))):
            params = params[1:-1]

        # Find the requested magics.
        m_line = shell.find_magic(target, 'line')
        m_cell = shell.find_magic(target, 'cell')
        if args.line and m_line is None:
            raise UsageError('Line magic function `%s%s` not found.' %
                             (magic_escapes['line'], target))
        if args.cell and m_cell is None:
            raise UsageError('Cell magic function `%s%s` not found.' %
                             (magic_escapes['cell'], target))

        # If --line and --cell are not specified, default to the ones
        # that are available.
        if not args.line and not args.cell:
            if not m_line and not m_cell:
                raise UsageError(
                    'No line or cell magic with name `%s` found.' % target
                )
            args.line = bool(m_line)
            args.cell = bool(m_cell)

        params_str = "" if params is None else " " + params

        if args.line:
            mman.register_alias(name, target, 'line', params)
            print('Created `%s%s` as an alias for `%s%s%s`.' % (
                magic_escapes['line'], name,
                magic_escapes['line'], target, params_str))

        if args.cell:
            mman.register_alias(name, target, 'cell', params)
            print('Created `%s%s` as an alias for `%s%s%s`.' % (
                magic_escapes['cell'], name,
                magic_escapes['cell'], target, params_str))