欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-10-26 23:08:40
问题 有没有办法告诉交互式python shell在会话之间保留其执行命令的历史记录? 当会话正在运行时,在执行命令之后,我可以向上箭头并访问所述命令,我只是想知道是否...

问题

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

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

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

解决方案

当然你可以用一个小的启动脚本。来自python教程中的:

# 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开始,:

现在,在支持的系统上的交互式解释器中默认启用tab-completion readline。默认情况下也会启用历史记录,并将其写入(并从中读取)文件~/.python-history。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。