예제 #1
0
파일: embed.py 프로젝트: rlugojr/ipython
    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 for the given call
        location. 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 Instance Option
        --------------------

        If for some reasons you need to kill the location where the instance is
        created and not called, for example if you create a single instance in
        one place and debug in many locations, you can use the ``--instance``
        option to kill this specific instance. Like for the ``call location``
        killing an "instance" should work even if it is recreated within a
        loop.

        .. note::

            This was the default behavior before IPython 5.2

        """

        args = magic_arguments.parse_argstring(self.kill_embedded, parameter_s)
        print(args)
        if args.instance:
            # let no ask
            if not args.yes:
                kill = ask_yes_no(
                    "Are you sure you want to kill this embedded instance? [y/N] ", 'n')
            else:
                kill = True
            if kill:
                self.shell._disable_init_location()
                print("This embedded IPython instance will not reactivate anymore "
                      "once you exit.")
        else:
            if not args.yes:
                kill = ask_yes_no(
                    "Are you sure you want to kill this embedded call_location? [y/N] ", 'n')
            else:
                kill = True
            if kill:
                self.shell.embedded_active = False
                print("This embedded IPython  call location will not reactivate anymore "
                      "once you exit.")

        if args.exit:
            # Ask-exit does not really ask, it just set internals flags to exit
            # on next loop.
            self.shell.ask_exit()
예제 #2
0
 def _on_all(self, cmd, *args, **kwargs):
     li = list(self)
     if len(li) > 1:
         answer = ask_yes_no('This will %s %d instances, ok? (y/N)' % (cmd, len(li)), default='n')
         if not answer:
             return
     for i in li:
         getattr(i, cmd)(*args, **kwargs)
     return Result(li, 'success')
예제 #3
0
 def run(self):
     print "Looks like this is the first time you are running iboto, let's configure an account:"
     more = True
     config = ConfigParser.RawConfigParser()
     while more:
         self.account(config)
         print 'iboto supports multiple accounts.'
         more = ask_yes_no('Would you like to configure another account? (y/n)')
         
     with file(self.filename, 'w') as fout:
         config.write(fout)
     print 'Configuration completed.'
     print 'To add or change accounts in future, edit ~/.iboto/settings.\n'
     prompt('Hit enter to continue to load iboto', allow_blank=True)
예제 #4
0
파일: embed.py 프로젝트: jamesgao/ipython
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.embedded_active = False
        print "This embedded IPython will not reactivate anymore once you exit."
예제 #5
0
파일: embed.py 프로젝트: monker490/WordVec
    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.")
예제 #6
0
파일: install.py 프로젝트: tango-cs/itango
def install(ipydir=None, verbose=True, profile='tango'):
    if verbose:
        def out(msg):
            sys.stdout.write(msg)
            sys.stdout.flush()
    else:
        out = lambda x: None

    ipython_dir = ipydir or get_ipython_dir()
    ensure_dir_exists(ipython_dir)
    try:
        p_dir = ProfileDir.find_profile_dir_by_name(ipython_dir, profile)
    except ProfileDirError:
        p_dir = ProfileDir.create_profile_dir_by_name(ipython_dir, profile)
    abs_config_file_name = os.path.join(p_dir.location, _CONFIG_FILE_NAME)
    create_config = True
    if os.path.isfile(abs_config_file_name):
        msg = "Tango configuration file {0} already exists.\n"
        msg += "Do you wish to replace it (y/n)?"
        msg = msg.format(abs_config_file_name)
        create_config = ask_yes_no(msg, default='y')

    if not create_config:
        return

    out("Installing tango extension to ipython... ")

    profile = __PROFILE.format(pytangover=tango.Release.version,
                               ipyver=IPython.release.version,
                               protected_block=__PROTECTED_BLOCK)
    with open(abs_config_file_name, "w") as f:
        f.write(profile)
        f.close()
    out("[DONE]\n\n")
    out("""\
To start ipython with tango interface simply type on the command line:
%% ipython --profile=tango

For more information goto:
http://pytango.readthedocs.io

Have fun with ITango!
The PyTango team
""")
예제 #7
0
def install(ipydir=None, verbose=True, profile='tango'):
    if verbose:

        def out(msg):
            sys.stdout.write(msg)
            sys.stdout.flush()
    else:
        out = lambda x: None

    ipython_dir = ipydir or get_ipython_dir()
    try:
        p_dir = ProfileDir.find_profile_dir_by_name(ipython_dir, profile)
    except ProfileDirError:
        p_dir = ProfileDir.create_profile_dir_by_name(ipython_dir, profile)
    abs_config_file_name = os.path.join(p_dir.location, _CONFIG_FILE_NAME)
    create_config = True
    if os.path.isfile(abs_config_file_name):
        create_config = ask_yes_no("Tango configuration file already exists. "\
                                   "Do you wish to replace it?", default='y')

    if not create_config:
        return

    out("Installing tango extension to ipython... ")

    profile = __PROFILE.format(pytangover=PyTango.Release.version,
                               ipyver=IPython.release.version)
    with open(abs_config_file_name, "w") as f:
        f.write(profile)
        f.close()
    out("[DONE]\n\n")
    out("""\
To start ipython with tango interface simply type on the command line:
%% ipython --profile=tango

For more information goto:
http://www.tango-controls.org/static/PyTango/latest/doc/html/

Have fun with ITango!
The PyTango team
""")
예제 #8
0
def install(ipydir=None, verbose=True, profile='tango'):
    if verbose:
        def out(msg):
            sys.stdout.write(msg)
            sys.stdout.flush()
    else:
        out = lambda x : None
    
    ipython_dir = ipydir or get_ipython_dir()
    try:
        p_dir = ProfileDir.find_profile_dir_by_name(ipython_dir, profile)
    except ProfileDirError:
        p_dir = ProfileDir.create_profile_dir_by_name(ipython_dir, profile)
    abs_config_file_name = os.path.join(p_dir.location, _CONFIG_FILE_NAME)
    create_config = True
    if os.path.isfile(abs_config_file_name):
        create_config = ask_yes_no("Tango configuration file already exists. "\
                                   "Do you wish to replace it?", default='y')
    
    if not create_config:
        return

    out("Installing tango extension to ipython... ")

    profile = __PROFILE.format(pytangover=PyTango.Release.version,
                               ipyver=IPython.release.version)
    with open(abs_config_file_name, "w") as f:
        f.write(profile)
        f.close()
    out("[DONE]\n\n")
    out("""\
To start ipython with tango interface simply type on the command line:
%% ipython --profile=tango

For more information goto:
http://www.tango-controls.org/static/PyTango/latest/doc/html/

Have fun with ITango!
The PyTango team
""")
예제 #9
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 = io.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(cast_unicode_py2(output), file=outfile)

        if close_at_end:
            outfile.close()
예제 #10
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)\\

    By default, input history is printed without line numbers so it can be
    directly pasted into an editor.

    With -n, each input's number <n> is shown, and is accessible as the
    automatically generated variable _i<n> as well as In[<n>].  Multi-line
    statements are printed starting at a new line for easy copy/paste.

    Options:

      -n: print line numbers for each input.
      This feature is only available if numbered prompts are in use.

      -o: also print outputs for each input.

      -p: print classic '>>>' python prompts before each input.  This is useful
       for making documentation, and in conjunction with -o, for producing
       doctest-ready output.

      -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.
    """

    if not self.outputcache.do_full_cache:
        print 'This feature is only available if numbered prompts are in use.'
        return
    opts,args = self.parse_options(parameter_s,'gnoptsrf:',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 = self.input_hist
    elif 'r' in opts:
        input_hist = self.input_hist_raw
    else:
        input_hist = self.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)-1
        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 >> Term.cout, self.magic_hist.__doc__
        return
    
    width = len(str(final))
    line_sep = ['','\n']
    print_nums = 'n' in opts
    print_outputs = 'o' in opts
    pyprompts = 'p' in opts
    
    found = False
    if pattern is not None:
        sh = self.shadowhist.all()
        for idx, s in sh:
            if fnmatch.fnmatch(s, pattern):
                print >> outfile, "0%d: %s" %(idx, s)
                found = True
    
    if found:
        print >> outfile, "==="
        print >> outfile, \
              "shadow history ends, fetch by %rep <number> (must start with 0)"
        print >> outfile, "=== 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]),
        if pyprompts:
            print >> outfile, '>>>',
            if multiline:
                lines = inline.splitlines()
                print >> outfile, '\n... '.join(lines)
                print >> outfile, '... '
            else:
                print >> outfile, inline,
        else:
            print >> outfile, inline,
        if print_outputs:
            output = self.shell.user_ns['Out'].get(in_num)
            if output is not None:
                print >> outfile, repr(output)

    if close_at_end:
        outfile.close()
예제 #11
0
 def start(self):
     if self.force or ask_yes_no("Really delete all ipython history? ",
             default="no", interrupt="no"):
         HistoryTrim.start(self)
예제 #12
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)\\

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

    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

    Options:

      -n: print line numbers for each input.
      This feature is only available if numbered prompts are in use.

      -o: also print outputs for each input.

      -p: print classic '>>>' python prompts before each input.  This is useful
       for making documentation, and in conjunction with -o, for producing
       doctest-ready output.

      -r: (default) print the 'raw' history, i.e. the actual commands you typed.
      
      -t: 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
      'get_ipython().magic("%cd /")' instead of '%cd /'.
      
      -g: treat the arg as a pattern to grep for in (full) history.
      This includes the saved history (almost all commands ever written).
      Use '%hist -g' to show full saved history (may be very long).
      
      -l: get the last n lines from all sessions. Specify n as a single arg, or
      the default is the last 10 lines.

      -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.
       
    Examples
    --------
    ::
    
      In [6]: %hist -n 4 6
      4:a = 12
      5:print a**2

    """

    if not self.shell.displayhook.do_full_cache:
        print('This feature is only available if numbered prompts are in use.')
        return
    opts,args = self.parse_options(parameter_s,'noprtglf:',mode='string')
    
    # 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.
    try:
        outfname = opts['f']
    except KeyError:
        outfile = io.stdout  # default
        # We don't want to close stdout at the end!
        close_at_end = False
    else:
        if os.path.exists(outfname):
            if not io.ask_yes_no("File %r exists. Overwrite?" % outfname): 
                print('Aborting.')
                return

        outfile = open(outfname,'w')
        close_at_end = True
    
    print_nums = 'n' in opts
    get_output = 'o' in opts
    pyprompts = 'p' in opts
    # Raw history is the default
    raw = not('t' in opts)
            
    default_length = 40
    pattern = None
    
    if 'g' in opts:         # Glob search
        pattern = "*" + args + "*" if args else "*"
        hist = history_manager.search(pattern, raw=raw, output=get_output)
    elif 'l' in opts:       # Get 'tail'
        try:
            n = int(args)
        except ValueError as IndexError:
            n = 10
        hist = history_manager.get_tail(n, raw=raw, output=get_output)
    else:
        if args:            # Get history by ranges
            hist = history_manager.get_range_by_str(args, 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('%s:%s' % (_format_lineno(session, lineno).rjust(width),
                    line_sep),  file=outfile, end='')
        if pyprompts:
            print(">>> ", end="", 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()
예제 #13
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)\\

    By default, input history is printed without line numbers so it can be
    directly pasted into an editor.

    With -n, each input's number <n> is shown, and is accessible as the
    automatically generated variable _i<n> as well as In[<n>].  Multi-line
    statements are printed starting at a new line for easy copy/paste.

    Options:

      -n: print line numbers for each input.
      This feature is only available if numbered prompts are in use.

      -o: also print outputs for each input.

      -p: print classic '>>>' python prompts before each input.  This is useful
       for making documentation, and in conjunction with -o, for producing
       doctest-ready output.

      -r: (default) print the 'raw' history, i.e. the actual commands you typed.
      
      -t: 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
      'get_ipython().magic("%cd /")' instead of '%cd /'.
      
      -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.
    """

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

    # Check if output to specific file was requested.
    try:
        outfname = opts['f']
    except KeyError:
        outfile = IPython.utils.io.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 = self.shell.history_manager.input_hist_parsed
    elif 'r' in opts:
        input_hist = self.shell.history_manager.input_hist_raw
    else:
        # Raw history is the default
        input_hist = self.shell.history_manager.input_hist_raw
            
    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)-1
        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__, file=IPython.utils.io.Term.cout)
        return
    
    width = len(str(final))
    line_sep = ['','\n']
    print_nums = 'n' in opts
    print_outputs = 'o' in opts
    pyprompts = 'p' in opts
    
    found = False
    if pattern is not None:
        sh = self.shell.history_manager.shadowhist.all()
        for idx, s in sh:
            if fnmatch.fnmatch(s, pattern):
                print("0%d: %s" %(idx, s.expandtabs(4)), file=outfile)
                found = True
    
    if found:
        print("===", file=outfile)
        print("shadow history ends, fetch by %rep <number> (must start with 0)",
              file=outfile)
        print("=== start of normal history ===", file=outfile)
        
    for in_num in range(init, final):
        # 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.
        inline = input_hist[in_num].expandtabs(4).rstrip()+'\n'

        if pattern is not None and not fnmatch.fnmatch(inline, pattern):
            continue
            
        multiline = int(inline.count('\n') > 1)
        if print_nums:
            print('%s:%s' % (str(in_num).ljust(width), line_sep[multiline]),
                  file=outfile)
        if pyprompts:
            print('>>>', file=outfile)
            if multiline:
                lines = inline.splitlines()
                print('\n... '.join(lines), file=outfile)
                print('... ', file=outfile)
            else:
                print(inline, end='', file=outfile)
        else:
            print(inline, end='', file=outfile)
        if print_outputs:
            output = self.shell.history_manager.output_hist.get(in_num)
            if output is not None:
                print(repr(output), file=outfile)

    if close_at_end:
        outfile.close()
예제 #14
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)\\

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

    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

    Options:

      -n: print line numbers for each input.
      This feature is only available if numbered prompts are in use.

      -o: also print outputs for each input.

      -p: print classic '>>>' python prompts before each input.  This is useful
       for making documentation, and in conjunction with -o, for producing
       doctest-ready output.

      -r: (default) print the 'raw' history, i.e. the actual commands you typed.
      
      -t: 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
      'get_ipython().magic("%cd /")' instead of '%cd /'.
      
      -g: treat the arg as a pattern to grep for in (full) history.
      This includes the saved history (almost all commands ever written).
      Use '%hist -g' to show full saved history (may be very long).
      
      -l: get the last n lines from all sessions. Specify n as a single arg, or
      the default is the last 10 lines.

      -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.
       
    Examples
    --------
    ::
    
      In [6]: %hist -n 4 6
      4:a = 12
      5:print a**2

    """

    if not self.shell.displayhook.do_full_cache:
        print('This feature is only available if numbered prompts are in use.')
        return
    opts, args = self.parse_options(parameter_s, 'noprtglf:', mode='string')

    # 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.
    try:
        outfname = opts['f']
    except KeyError:
        outfile = io.stdout  # default
        # We don't want to close stdout at the end!
        close_at_end = False
    else:
        if os.path.exists(outfname):
            if not io.ask_yes_no("File %r exists. Overwrite?" % outfname):
                print('Aborting.')
                return

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

    print_nums = 'n' in opts
    get_output = 'o' in opts
    pyprompts = 'p' in opts
    # Raw history is the default
    raw = not ('t' in opts)

    default_length = 40
    pattern = None

    if 'g' in opts:  # Glob search
        pattern = "*" + args + "*" if args else "*"
        hist = history_manager.search(pattern, raw=raw, output=get_output)
    elif 'l' in opts:  # Get 'tail'
        try:
            n = int(args)
        except ValueError, IndexError:
            n = 10
        hist = history_manager.get_tail(n, raw=raw, output=get_output)
예제 #15
0
파일: history.py 프로젝트: 2t7/ipython
    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 = io.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(cast_unicode_py2(output), file=outfile)

        if close_at_end:
            outfile.close()
예제 #16
0
파일: history.py 프로젝트: Tremere/ipython
def magic_history(self, parameter_s = ''):
    """Print input history (_i<n> variables), with most recent last.

    %history [-o -p -t -n] [-f filename] [range | -g pattern | -l number]

    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

    Options:

      -n: print line numbers for each input.
      This feature is only available if numbered prompts are in use.

      -o: also print outputs for each input.

      -p: print classic '>>>' python prompts before each input.  This is useful
       for making documentation, and in conjunction with -o, for producing
       doctest-ready output.

      -r: (default) print the 'raw' history, i.e. the actual commands you typed.

      -t: 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
      'get_ipython().magic("%cd /")' instead of '%cd /'.

      -g: treat the arg as a pattern to grep for in (full) history.
      This includes the saved history (almost all commands ever written).
      Use '%hist -g' to show full saved history (may be very long).

      -l: get the last n lines from all sessions. Specify n as a single arg, or
      the default is the last 10 lines.

      -f FILENAME: instead of printing the output to the screen, redirect it to
       the given file.  The file is always overwritten, though *when it can*,
       IPython asks for confirmation first. In particular, running the command
       "history -f FILENAME" from the IPython Notebook interface will replace
       FILENAME even if it already exists *without* confirmation.

    Examples
    --------
    ::

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

    """

    if not self.shell.displayhook.do_full_cache:
        print('This feature is only available if numbered prompts are in use.')
        return
    opts,args = self.parse_options(parameter_s,'noprtglf:',mode='string')

    # 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.
    try:
        outfname = opts['f']
    except KeyError:
        outfile = io.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 = 'n' in opts
    get_output = 'o' in opts
    pyprompts = 'p' in opts
    # Raw history is the default
    raw = not('t' in opts)

    default_length = 40
    pattern = None

    if 'g' in opts:         # Glob search
        pattern = "*" + args + "*" if args else "*"
        hist = history_manager.search(pattern, raw=raw, output=get_output)
        print_nums = True
    elif 'l' in opts:       # Get 'tail'
        try:
            n = int(args)
        except ValueError, IndexError:
            n = 10
        hist = history_manager.get_tail(n, raw=raw, output=get_output)
예제 #17
0
    def history(self, parameter_s=''):
        """Print input history (_i<n> variables), with most recent last.

        %history [-o -p -t -n] [-f filename] [range | -g pattern | -l number]

        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

        Options:

          -n: print line numbers for each input.
          This feature is only available if numbered prompts are in use.

          -o: also print outputs for each input.

          -p: print classic '>>>' python prompts before each input.  This is
           useful for making documentation, and in conjunction with -o, for
           producing doctest-ready output.

          -r: (default) print the 'raw' history, i.e. the actual commands you
           typed.

          -t: 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 'get_ipython().magic("%cd /")' instead of '%cd /'.

          -g: treat the arg as a pattern to grep for in (full) history.
          This includes the saved history (almost all commands ever written).
          Use '%hist -g' to show full saved history (may be very long).

          -l: get the last n lines from all sessions. Specify n as a single
          arg, or the default is the last 10 lines.

          -f FILENAME: instead of printing the output to the screen, redirect
           it to the given file.  The file is always overwritten, though *when
           it can*, IPython asks for confirmation first. In particular, running
           the command 'history -f FILENAME' from the IPython Notebook
           interface will replace FILENAME even if it already exists *without*
           confirmation.

        Examples
        --------
        ::

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

        """

        if not self.shell.displayhook.do_full_cache:
            print('This feature is only available if numbered prompts '
                  'are in use.')
            return
        opts, args = self.parse_options(parameter_s,
                                        'noprtglf:',
                                        mode='string')

        # 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.
        try:
            outfname = opts['f']
        except KeyError:
            outfile = io.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 = 'n' in opts
        get_output = 'o' in opts
        pyprompts = 'p' in opts
        # Raw history is the default
        raw = not ('t' in opts)

        pattern = None

        if 'g' in opts:  # Glob search
            pattern = "*" + args + "*" if args else "*"
            hist = history_manager.search(pattern, raw=raw, output=get_output)
            print_nums = True
        elif 'l' in opts:  # Get 'tail'
            try:
                n = int(args)
            except (ValueError, IndexError):
                n = 10
            hist = history_manager.get_tail(n, raw=raw, output=get_output)
        else:
            if args:  # Get history by ranges
                hist = history_manager.get_range_by_str(args, 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('%s:%s' %
                      (_format_lineno(session, lineno).rjust(width), line_sep),
                      file=outfile,
                      end='')
            if pyprompts:
                print(">>> ", end="", 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()