您可以通过在一个启动脚本(例如$(ipython locate profile)/startup/log_history.py)中添加该脚本来模拟bash的行为: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(completion,^R search等)可以使用一些您喜欢的手动命令进行版本控制,则此启动文件将允许您自己维护该文件,这将纯粹是对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/目录中,然后编辑profile_default/readline_favorites,或者保存该文件的任何地方,它将显示在每个IPython会话的readline completions中,等等。