4/03/2006

Writing your Python REPL history to a file

Something I have often wished for is the ability to save the history of a Python interactive session to a file. I often screw around in the interpreter to figure out how I am going to implement something, and it is tedious to go through and copy/paste all the lines out of the terminal into an editor and clean it up. Luckily, I discovered there is an easier way in the readline module:




import readline
readline.write_history_file('my_history.py')


I'm sure this is going to come in handy many times.



5 comments:

drew said...

dude- get ipython. It's constantly writing your history to ~/.ipython/history, and it has a pile of other great features. The first one you'll notice is probably the tab completion.

Donovan Preston said...

I know, I know. :-) I have ipython installed. However I haven't found it compelling enough to use it very often. The tab completion might do it though. There are two things that really annoy me about it:
It takes too long to load :-)
It asks me if I'm sure I want to exit when I press Control-D. Yes, I want to exit. I pressed Control-D.
The first one is probably not fixable, but the second one might be. Any clue how to fix it?

drew said...

My .ipython/ipythonrc contains a line "confirm_exit 0" which probably turns off that silly confirmation. I also used to experience the too-long-to-load, and I'm not sure if that went away as I moved to faster boxes or whether I did other configuration to cut down on the loaded modules.
There is a -quick option, but I don't think it's actually what you want :)

Donovan Preston said...

Awesome, thanks. I'm moving to a MacBook Pro sometime soon, so we'll see if that helps with the loading times.

Abe said...

Thanks for the tip, that's good to know. And thanks drew for recomending iPython. I just did an apt-get install ipython, so we'll see how it goes.