为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黑洞网,csdn同步更新

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值