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

yipeiwu_com6年前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给图片添加半透明水印

如何利用python给图片添加半透明水印

前言 本文主要给大家介绍了关于python图片添加半透明水印的相关资料,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧 示例代码: # coding:utf-8 f...

python 利用pywifi模块实现连接网络破解wifi密码实时监控网络

python 利用pywifi模块实现连接网络破解wifi密码实时监控网络,具体内容如下: import pywifi from pywifi import * import tim...

Python3中的bytes和str类型详解

Python 3最重要的新特性之一是对字符串和二进制数据流做了明确的区分。文本总是Unicode,由str类型表示,二进制数据则由bytes类型表示。Python 3不会以任意隐式的方式...

Python实现语音识别和语音合成功能

Python实现语音识别和语音合成功能

声音的本质是震动,震动的本质是位移关于时间的函数,波形文件(.wav)中记录了不同采样时刻的位移。 通过傅里叶变换,可以将时间域的声音函数分解为一系列不同频率的正弦函数的叠加,通过频率谱...

python redis 删除key脚本的实例

单机模式 代码片段 安装 pip install redis import redis r = redis.Redis(host='192.168.1.3', port=6188,d...