为Python终端提供持久的历史记录 [英] Give the Python Terminal a Persistent History
问题描述
有没有办法告诉交互式Python shell在会话之间保留其已执行命令的历史?
Is there a way to tell the interactive Python shell to preserve its history of executed commands between sessions?
在运行会话的同时,执行完命令后,我可以向上箭头访问这些命令,我只是想知道是否存在某种方式可以保存一定数量的这些命令,直到下次使用Python外壳程序.
While a session is running, after commands have been executed, I can arrow up and access said commands, I'm just wondering if there is some way for a certain number of these commands to be saved until the next time I use the Python shell.
这将非常有用,因为我发现自己在上次会话结束时使用的会话中重用命令.
This would be very useful since I find myself reusing commands in a session, that I used at the end of the last session.
推荐答案
可以,只需一个小的启动脚本即可.来自python教程中的交互式输入编辑和历史记录替换:
Sure you can, with a small startup script. From Interactive Input Editing and History Substitution in the python tutorial:
# 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开始,交互式解释器支持自动补全和历史记录功能盒子:
From Python 3.4 onwards, the interactive interpreter supports autocompletion and history out of the box:
现在,在支持readline
的系统上,交互式解释器中默认启用了Tab-completion.默认情况下,历史记录也处于启用状态,并且被写入(和读取)文件 ~/.python-history
.
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
.
这篇关于为Python终端提供持久的历史记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!