How do you see the entire command history in interactive Python?

后端 未结 10 1735
不知归路
不知归路 2020-11-30 16:36

I\'m working on the default python interpreter on Mac OS X, and I Cmd+K (cleared) my earlier commands. I can go through them one by one using the arrow

相关标签:
10条回答
  • 2020-11-30 17:16

    @Jason-V, it really help, thanks. then, i found this examples and composed to own snippet.

    #!/usr/bin/env python3
    import os, readline, atexit
    python_history = os.path.join(os.environ['HOME'], '.python_history')
    try:
      readline.read_history_file(python_history)
      readline.parse_and_bind("tab: complete")
      readline.set_history_length(5000)
      atexit.register(readline.write_history_file, python_history)
    except IOError:
      pass
    del os, python_history, readline, atexit 
    
    0 讨论(0)
  • 2020-11-30 17:16

    This should give you the commands printed out in separate lines:

    import readline
    map(lambda p:print(readline.get_history_item(p)),
        map(lambda p:p, range(readline.get_current_history_length()))
    )
    
    0 讨论(0)
  • 2020-11-30 17:17

    Rehash of Doogle's answer that doesn't printline numbers, but does allow specifying the number of lines to print.

    def history(lastn=None):
        """
        param: lastn Defaults to None i.e full history. If specified then returns lastn records from history.
               Also takes -ve sequence for first n history records.
        """
        import readline
        assert lastn is None or isinstance(lastn, int), "Only integers are allowed."
        hlen = readline.get_current_history_length()
        is_neg = lastn is not None and lastn < 0
        if not is_neg:
            for r in range(1,hlen+1) if not lastn else range(1, hlen+1)[-lastn:]:
                print(readline.get_history_item(r))
        else:
            for r in range(1, -lastn + 1):
                print(readline.get_history_item(r))
    
    0 讨论(0)
  • 2020-11-30 17:19

    Since the above only works for python 2.x for python 3.x (specifically 3.5) is similar but with a slight modification:

    import readline
    for i in range(readline.get_current_history_length()):
        print (readline.get_history_item(i + 1))
    

    note the extra ()

    (using shell scripts to parse .python_history or using python to modify the above code is a matter of personal taste and situation imho)

    0 讨论(0)
提交回复
热议问题