您可以通过在其中一个启动脚本中添加它来模拟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完成等中.