经过搜索和查看IPython的documentation和一些code后,我似乎无法弄清楚是否可以将命令历史记录(而不是输出日志)存储到文本文件而不是SQLite数据库中。 ipython --help-all
似乎表明此选项不存在。
这对于版本控制频繁使用的命令非常有用,就像在.bash_history中一样。
编辑:基于@minrk的答案,Working solution已经可行。
经过搜索和查看IPython的documentation和一些code后,我似乎无法弄清楚是否可以将命令历史记录(而不是输出日志)存储到文本文件而不是SQLite数据库中。 ipython --help-all
似乎表明此选项不存在。
这对于版本控制频繁使用的命令非常有用,就像在.bash_history中一样。
编辑:基于@minrk的答案,Working solution已经可行。
您还可以选择想要保存的行。例如:
%history 1 7-8 10 -f /tmp/bar.py
这将把第1行、第7至8行和第10行保存到一个名为bar.py的临时文件中。如果需要完整内容,只需跳过这些行即可。
%history -f /tmp/foo.py
保存Ipython会话历史记录:
%save [filename] [line start - line end]
%save ~/Desktop/Ipython_session.txt 1-31
这只会保存特定的IPython会话历史,但不会保存整个IPython命令历史记录。
$(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)
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会话的读取行完成等中。
?%history
命令还可以展示如何提取日志的特定部分,比如活动会话。 - Anton Tarasenkohistory -g
。 - Aaron Swan