Skip to content

Instantly share code, notes, and snippets.

@minrk
Last active December 17, 2015 23:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save minrk/5686821 to your computer and use it in GitHub Desktop.
Save minrk/5686821 to your computer and use it in GitHub Desktop.
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment