python清除历史记录_如何将IPython历史记录到文本文件?

您可以通过在其中一个启动脚本中添加它来模拟bash的行为(例如$(ipython locate profile)/startup/log_history.py:

import atexit

import os

ip = get_ipython()

LIMIT = 1000 # limit the size of the history

def save_history():

"""save the IPython history to a plaintext file"""

histfile = os.path.join(ip.profile_dir.location, "history.txt")

print("Saving plaintext history to %s" % histfile)

lines = []

# get previous lines

# this is only necessary because we truncate the history,

# otherwise we chould just open with mode='a'

if os.path.exists(histfile):

with open(histfile, 'r') as f:

lines = f.readlines()

# add any new lines from this session

lines.extend(record[2] + '\n' for record in ip.history_manager.get_range())

with open(histfile, 'w') as f:

# limit to LIMIT entries

f.writelines(lines[-LIMIT:])

# do the save at exit

atexit.register(save_history)

请注意,这会模拟bash / readline历史行为,因为它会在解释器崩溃时失败等.

更新:替代方案

如果您真正想要的是只有一些手动收藏命令可用于readline(完成,^ R搜索等),您可以进行版本控制,这个启动文件将允许您自己维护该文件,这将纯粹是除了IPython的实际命令历史记录:

import os

ip = get_ipython()

favfile = "readline_favorites"

def load_readline_favorites():

"""load profile_dir/readline_favorites into the readline history"""

path = os.path.join(ip.profile_dir.location, favfile)

if not os.path.exists(path):

return

with open(path) as f:

for line in f:

ip.readline.add_history(line.rstrip('\n'))

if ip.has_readline:

load_readline_favorites()

将其放在profile_default / startup / dir中,然后编辑profile_default / readline_favorites,或者您希望保留该文件的任何位置,它将在每个IPython会话中显示在readline完成等中.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值