为Python终端提供持久性历史记录

时间:2012-09-08 20:43:36

标签: python linux python-2.7

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

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

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

3 个答案:

答案 0 :(得分:39)

当然,你可以使用一个小的启动脚本。来自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的系统上的交互式解释器中启用了Tab-completion。默认情况下也会启用历史记录,并将其写入(并从中读取)文件~/.python-history

答案 1 :(得分:17)

使用IPython

无论如何,你应该这样做,因为它很棒:持久的命令历史只是众多方式中的一种,它比现有的Python shell更好。

答案 2 :(得分:0)

使用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)