【问题标题】:Give the Python Terminal a Persistent History给 Python 终端一个持久的历史
【发布时间】:2012-09-02 07:03:39
【问题描述】:

有没有办法告诉交互式 Python shell 保留会话之间执行命令的历史记录?

在会话运行时,在执行命令后,我可以向上箭头并访问所述命令,我只是想知道是否有某种方法可以保存一定数量的这些命令,直到我下次使用Python shell。

这将非常有用,因为我发现自己在会话中重复使用了在上次会话结束时使用的命令。

【问题讨论】:

标签: python linux python-2.7


【解决方案1】:

在使用virtual environment 时,这对于 Python 3 也是必需的。

我使用一个稍微不同的版本,它为每个虚拟环境保留一个历史文件:

import sys

if sys.version_info >= (3, 0) and hasattr(sys, 'real_prefix'):  # in a VirtualEnv
    import atexit, os, readline, sys

    PYTHON_HISTORY_FILE = os.path.join(os.environ['VIRTUAL_ENV'], '.python_history')
    if os.path.exists(PYTHON_HISTORY_FILE):
        readline.read_history_file(PYTHON_HISTORY_FILE)
    atexit.register(readline.write_history_file, PYTHON_HISTORY_FILE)

【讨论】:

    【解决方案2】:

    当然可以,只需一个小的启动脚本。来自python教程中的Interactive Input Editing and History Substitution

    # Add auto-completion and a stored history file of commands to your Python
    # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
    # bound to the Esc key by default (you can change it - see readline docs).
    #
    # Store the file in ~/.pystartup, and set an environment variable to point
    # to it:  "export PYTHONSTARTUP=~/.pystartup" in bash.
    
    import atexit
    import os
    import readline
    import rlcompleter
    
    historyPath = os.path.expanduser("~/.pyhistory")
    
    def save_history(historyPath=historyPath):
        import readline
        readline.write_history_file(historyPath)
    
    if os.path.exists(historyPath):
        readline.read_history_file(historyPath)
    
    atexit.register(save_history)
    del os, atexit, readline, rlcompleter, save_history, historyPath
    

    从 Python 3.4 开始,the interactive interpreter supports autocompletion and history out of the box

    现在在支持readline 的系统上的交互式解释器中默认启用制表符补全。默认情况下也启用历史记录,并写入(和读取)文件~/.python-history

    【讨论】:

    • 谢谢,这就是我要找的!
    • 我有几个 python 虚拟环境,希望能够启用持久历史记录。所以采用了这种方式,只是将.pyhistory文件的位置改为虚拟环境文件夹,而不是用户主文件夹。
    【解决方案3】:

    使用IPython

    无论如何,你应该这样做,因为它太棒了:持久的命令历史记录只是它比普通 Python shell 更好的众多方式之一。

    【讨论】:

    • 特别棒:我刚刚注意到它现在支持 Python 3!
    猜你喜欢
    • 2023-04-08
    • 2017-01-22
    • 1970-01-01
    • 2013-05-04
    • 2022-06-14
    • 1970-01-01
    • 2018-07-25
    • 2014-11-02
    • 2021-05-27
    相关资源
    最近更新 更多