def kill_embedded(self,parameter_s=''):
    """%kill_embedded : deactivate for good the current embedded IPython.

    This function (after asking for confirmation) sets an internal flag so that
    an embedded IPython will never activate again.  This is useful to
    permanently disable a shell that is being called inside a loop: once you've
    figured out what you needed from it, you may then kill it and the program
    will then continue to run without the interactive shell interfering again.
    """
    
    kill = ask_yes_no("Are you sure you want to kill this embedded instance "
                     "(y/n)? [y/N] ",'n')
    if kill:
        self.shell.embedded_active = False
        print "This embedded IPython will not reactivate anymore once you exit."
Example #2
0
def _quit_sage_(self):
    import sage.misc.preparser_ipython
    if sage.misc.preparser_ipython.interface != None:
        sage.misc.preparser_ipython.switch_interface('sage')
        self.exit_now = False
        return

    from IPython.genutils import ask_yes_no
    if self.rc.confirm_exit:
        if ask_yes_no('Do you really want to exit ([y]/n)?', 'y'):
            self.exit_now = True
    else:
        self.exit_now = True
    if self.exit_now:
        quit_sage()
        self.exit_now = True

    return self.exit_now
Example #3
0
def _quit_sage_(self):
    import sage.misc.preparser_ipython
    if sage.misc.preparser_ipython.interface != None:
        sage.misc.preparser_ipython.switch_interface('sage')
        self.exit_now = False
        return
    
    from IPython.genutils import ask_yes_no
    if self.rc.confirm_exit:
        if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
            self.exit_now = True
    else:
        self.exit_now = True
    if self.exit_now:
        quit_sage()
        self.exit_now = True

    return self.exit_now
Example #4
0
def magic_history(self, parameter_s=''):
    """Print input history (_i<n> variables), with most recent last.
    
    %history       -> print at most 40 inputs (some may be multi-line)\\
    %history n     -> print at most n inputs\\
    %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
    
    Each input's number <n> is shown, and is accessible as the
    automatically generated variable _i<n>.  Multi-line statements are
    printed starting at a new line for easy copy/paste.
    

    Options:

      -n: do NOT print line numbers. This is useful if you want to get a
      printout of many lines which can be directly pasted into a text
      editor.

      This feature is only available if numbered prompts are in use.

      -t: (default) print the 'translated' history, as IPython understands it.
      IPython filters your input and converts it all into valid Python source
      before executing it (things like magics or aliases are turned into
      function calls, for example). With this option, you'll see the native
      history instead of the user-entered version: '%cd /' will be seen as
      '_ip.magic("%cd /")' instead of '%cd /'.
      
      -r: print the 'raw' history, i.e. the actual commands you typed.
      
      -g: treat the arg as a pattern to grep for in (full) history.
      This includes the "shadow history" (almost all commands ever written).
      Use '%hist -g' to show full shadow history (may be very long).
      In shadow history, every index nuwber starts with 0.

      -f FILENAME: instead of printing the output to the screen, redirect it to
       the given file.  The file is always overwritten, though IPython asks for
       confirmation first if it already exists.
    """

    ip = self.api
    shell = self.shell
    if not shell.outputcache.do_full_cache:
        print 'This feature is only available if numbered prompts are in use.'
        return
    opts, args = self.parse_options(parameter_s, 'gntsrf:', mode='list')

    # Check if output to specific file was requested.
    try:
        outfname = opts['f']
    except KeyError:
        outfile = Term.cout  # default
        # We don't want to close stdout at the end!
        close_at_end = False
    else:
        if os.path.exists(outfname):
            if not ask_yes_no("File %r exists. Overwrite?" % outfname):
                print 'Aborting.'
                return

        outfile = open(outfname, 'w')
        close_at_end = True

    if 't' in opts:
        input_hist = shell.input_hist
    elif 'r' in opts:
        input_hist = shell.input_hist_raw
    else:
        input_hist = shell.input_hist

    default_length = 40
    pattern = None
    if 'g' in opts:
        init = 1
        final = len(input_hist)
        parts = parameter_s.split(None, 1)
        if len(parts) == 1:
            parts += '*'
        head, pattern = parts
        pattern = "*" + pattern + "*"
    elif len(args) == 0:
        final = len(input_hist)
        init = max(1, final - default_length)
    elif len(args) == 1:
        final = len(input_hist)
        init = max(1, final - int(args[0]))
    elif len(args) == 2:
        init, final = map(int, args)
    else:
        warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
        print self.magic_hist.__doc__
        return
    width = len(str(final))
    line_sep = ['', '\n']
    print_nums = not opts.has_key('n')

    found = False
    if pattern is not None:
        sh = ip.IP.shadowhist.all()
        for idx, s in sh:
            if fnmatch.fnmatch(s, pattern):
                print "0%d: %s" % (idx, s)
                found = True

    if found:
        print "==="
        print "shadow history ends, fetch by %rep <number> (must start with 0)"
        print "=== start of normal history ==="

    for in_num in range(init, final):
        inline = input_hist[in_num]
        if pattern is not None and not fnmatch.fnmatch(inline, pattern):
            continue

        multiline = int(inline.count('\n') > 1)
        if print_nums:
            print >> outfile, \
                  '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
        print >> outfile, inline,

    if close_at_end:
        outfile.close()
Example #5
0
def magic_history(self, parameter_s = ''):
    """Print input history (_i<n> variables), with most recent last.
    
    %history       -> print at most 40 inputs (some may be multi-line)\\
    %history n     -> print at most n inputs\\
    %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
    
    Each input's number <n> is shown, and is accessible as the
    automatically generated variable _i<n>.  Multi-line statements are
    printed starting at a new line for easy copy/paste.
    

    Options:

      -n: do NOT print line numbers. This is useful if you want to get a
      printout of many lines which can be directly pasted into a text
      editor.

      This feature is only available if numbered prompts are in use.

      -t: (default) print the 'translated' history, as IPython understands it.
      IPython filters your input and converts it all into valid Python source
      before executing it (things like magics or aliases are turned into
      function calls, for example). With this option, you'll see the native
      history instead of the user-entered version: '%cd /' will be seen as
      '_ip.magic("%cd /")' instead of '%cd /'.
      
      -r: print the 'raw' history, i.e. the actual commands you typed.
      
      -g: treat the arg as a pattern to grep for in (full) history.
      This includes the "shadow history" (almost all commands ever written).
      Use '%hist -g' to show full shadow history (may be very long).
      In shadow history, every index nuwber starts with 0.

      -f FILENAME: instead of printing the output to the screen, redirect it to
       the given file.  The file is always overwritten, though IPython asks for
       confirmation first if it already exists.
      

    """

    ip = self.api
    shell = self.shell
    if not shell.outputcache.do_full_cache:
        print 'This feature is only available if numbered prompts are in use.'
        return
    opts,args = self.parse_options(parameter_s,'gntsrf:',mode='list')

    # Check if output to specific file was requested.
    try:
        outfname = opts['f']
    except KeyError:
        outfile = Term.cout
        # We don't want to close stdout at the end!
        close_at_end = False
    else:
        if os.path.exists(outfname):
            ans = ask_yes_no("File %r exists. Overwrite?" % outfname)
            if not ans:
                print 'Aborting.'
                return
            else:
                outfile = open(outfname,'w')
                close_at_end = True
                

    if opts.has_key('t'):
        input_hist = shell.input_hist
    elif opts.has_key('r'):
        input_hist = shell.input_hist_raw
    else:
        input_hist = shell.input_hist
        
    
    default_length = 40
    pattern = None
    if opts.has_key('g'):
        init = 1
        final = len(input_hist)
        parts = parameter_s.split(None,1)
        if len(parts) == 1:
            parts += '*'
        head, pattern = parts
        pattern = "*" + pattern + "*"
    elif len(args) == 0:
        final = len(input_hist)
        init = max(1,final-default_length)
    elif len(args) == 1:
        final = len(input_hist)
        init = max(1,final-int(args[0]))
    elif len(args) == 2:
        init,final = map(int,args)
    else:
        warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
        print self.magic_hist.__doc__
        return
    width = len(str(final))
    line_sep = ['','\n']
    print_nums = not opts.has_key('n')
    
    found = False
    if pattern is not None:
        sh = ip.IP.shadowhist.all()
        for idx, s in sh:
            if fnmatch.fnmatch(s, pattern):
                print "0%d: %s" %(idx, s)
                found = True
    
    if found:
        print "==="
        print "shadow history ends, fetch by %rep <number> (must start with 0)"
        print "=== start of normal history ==="
        
    for in_num in range(init,final):        
        inline = input_hist[in_num]
        if pattern is not None and not fnmatch.fnmatch(inline, pattern):
            continue
            
        multiline = int(inline.count('\n') > 1)
        if print_nums:
            print >> outfile, \
                  '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
        print >> outfile, inline,

    if close_at_end:
        outfile.close()