给Python终端一个持久的历史记录

2024-05-23 17:56:43 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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


Tags: 方法命令历史记录数量箭头shell执行命令
3条回答

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

当然可以,只要一个小的启动脚本。来自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

Tab-completion is now enabled by default in the interactive interpreter on systems that support readline. History is also enabled by default, and is written to (and read from) the file ~/.python-history.

使用IPython

无论如何,您应该这样做,因为它太棒了:持久的命令历史只是许多方法中的一种,它比一般的Python shell要好。

相关问题 更多 >