Kevin Burke Kevin Burke - 1 year ago 194
Python Question

Export Python interpreter history to a file?

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?

For example

>>> a = 5
>>> b = a + 6
>>> import sys
>>> export('history', '')

And then I can open the
file and read:

a = 5
b = a + 6
import sys

Answer Source

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 (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

if os.path.exists(historyPath):

del os, atexit, readline, rlcompleter, save_history, historyPath

You can also add this to get autocomplete for free:

readline.parse_and_bind('tab: complete')

Please note that this will only work on *nix systems. As readline is only available in Unix platform.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download