如何为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设计】。

相关文章

完美解决Pycharm无法导入包的问题 Unresolved reference

完美解决Pycharm无法导入包的问题 Unresolved reference

如下所示: Unresolved reference 'ERROR_CODE_INPUT_ERROR' less... (Ctrl+F1) This inspection dete...

Python StringIO如何在内存中读写str

这篇文章主要介绍了python StringIO如何在内存中读写str,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 StringIO...

pytorch实现建立自己的数据集(以mnist为例)

pytorch实现建立自己的数据集(以mnist为例)

本文将原始的numpy array数据在pytorch下封装为Dataset类的数据集,为后续深度网络训练提供数据。 加载并保存图像信息 首先导入需要的库,定义各种路径。 impor...

Python numpy线性代数用法实例解析

Python numpy线性代数用法实例解析

这篇文章主要介绍了Python numpy线性代数用法实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 numpy中线性代数用法...

Python3.8对可迭代解包的改进及用法详解

Python 3 的可迭代解包 在 PEP 3132 - Extended Iterable Unpacking 里面描述了一种对可迭代对象的解包用法,Python 3 可用: In...