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

yipeiwu_com5年前Python基础

问题

有没有办法告诉交互式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。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python写的PHPMyAdmin暴力破解工具代码

PHPMyAdmin暴力破解,加上CVE-2012-2122 MySQL Authentication Bypass Vulnerability漏洞利用。 #!/usr/bin/en...

Python生成不重复随机值的方法

本文实例讲述了Python生成不重复随机值的方法。分享给大家供大家参考。具体分析如下: 这里从一列表中,生成不重复的随机值 算法实现如下: import random total =...

Python虚拟环境的原理及使用详解

Python的虚拟环境极大地方便了人们的生活。本指南先介绍虚拟环境的基础知识以及使用方法,然后再深入介绍虚拟环境背后的工作原理。 注意:本指南在macOS Mojave系统上使用最新版本...

django 中的聚合函数,分组函数,F 查询,Q查询

先以mysql的语句,聚合用在分组里, 对mysql中groupby 是分组 每什么的时候就要分组,如 每个小组,就按小组分, group by 字段 having 聚合函数 #举例 :...

Python 窗体(tkinter)按钮 位置实例

如下所示: import tkinter def go(): #函数 print("go函数") win=tkinter.Tk() #构造窗体 win.title("he...