Many times I will use the Python interpreter to inspect variables and step through commands before I actually write to a file. However by the end I have around 30 commands in the interpreter, and have to copy/paste them into a file to run. Is there a way I can export/write the Python interpreter history into a file?
>>> a = 5
>>> b = a + 6
>>> import sys
>>> export('history', 'interactions.py')
a = 5
b = a + 6
IPython is extremely useful if you like using interactive sessions. For example for your usecase there is the save command, you just input save my_useful_session 10-20 23 to save input lines 10 to 20 and 23 to my_useful_session.py. (to help with this, every line is prefixed by its number)
Look at the videos on the documentation page to get a quick overview of the features.
There is a way to do it. Store the file in ~/.pystartup
# Add auto-completion and a stored history file of commands to your Python # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is # bound to the Esc key by default (you can change it - see readline docs). # # Store the file in ~/.pystartup, and set an environment variable to point # to it: "export PYTHONSTARTUP=/home/user/.pystartup" in bash. # # Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the # full path to your home directory. import atexit import os import readline import rlcompleter historyPath = os.path.expanduser("~/.pyhistory") def save_history(historyPath=historyPath): import readline readline.write_history_file(historyPath) if os.path.exists(historyPath): readline.read_history_file(historyPath) atexit.register(save_history) del os, atexit, readline, rlcompleter, save_history, historyPath
You can also add this to get autocomplete for free:
Please note that this will only work on *nix systems. As readline is only available in Unix platform.