Kevin Burke
Kevin Burke

Reputation: 64834

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', 'interactions.py') 

And then I can open the interactions.py file and read:

a = 5
b = a + 6
import sys

Upvotes: 26

Views: 26705

Answers (7)

user13518412
user13518412

Reputation: 7

why do you want to write the code from interpreter to python file? you use interpreters to test your code, and so you can write same code in your program. Or you can create you own interpreter that can save commands in a file.

#shell.py
import code, sys
class Shell(code.InteractiveConsole):
    def write(self, s):
        open("history.cmd", "a").write(f"{s}\n")
        sys.stderr.write(f"{s}")
    def raw_input(self, prompt):
        a = input(prompt)
        open("history.cmd", "a").write(f"{prompt}{a}\n")
        return a
if __name__ == "__main__": # run the program only if runned
    shell = Shell(filename="<stdin>") #you can use your own filename
    shell.interact()

You can inherit this class in your own class and create your own interpreter!

Upvotes: -2

nealmcb
nealmcb

Reputation: 13471

Much has changed over the last 8 years since this question was asked.

It appears that since Python 3.4, history is automatically written to ~/.python_history as a plain text file.

If you want to disable that or learn more, check out

And, of course, as noted by many others, IPython has great features for saving, searching and manipulating history. Learn more via %history?

Upvotes: 13

Ishan Tomar
Ishan Tomar

Reputation: 1554

In ipython shell:

%history 

The command will print all the commands you have entered in the current python shell.

% history -g 

The command will print all the commands logged in python shell upto some significant number of lines.

%history -g -f history.log 

Will write the logged commands along with the line number. you can remove the fixed width line numbers for the commands of interest using gvim.

Upvotes: 2

Mr. Elusive
Mr. Elusive

Reputation: 496

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.

::OR::

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:

readline.parse_and_bind('tab: complete')

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

Upvotes: 26

pyfunc
pyfunc

Reputation: 66709

If you are using Linux/Mac and have readline library, you could add the following to a file and export it in your .bash_profile and you will have both completion and history.

# python startup file
import readline
import rlcompleter
import atexit
import os
# tab completion
readline.parse_and_bind('tab: complete')
# history file
histfile = os.path.join(os.environ['HOME'], '.pythonhistory')
try:
    readline.read_history_file(histfile)
except IOError:
    pass
atexit.register(readline.write_history_file, histfile)
del os, histfile, readline, rlcompleter

Export command:

export PYTHONSTARTUP=path/to/.pythonstartup

This will save your python console history at ~/.pythonhistory

Upvotes: 12

user688996
user688996

Reputation: 173

Python on Linux should have history support via readline library, see http://docs.python.org/tutorial/interactive.html

Upvotes: 0

mac
mac

Reputation: 43031

The following is not my own work, but frankly I don't remember where I first got it... However: place the following file (on a GNU/Linux system) in your home folder (the name of the file should be .pystartup.py):

# 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, e.g. "export PYTHONSTARTUP=/max/home/itamar/.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")
historyTmp = os.path.expanduser("~/.pyhisttmp.py")

endMarkerStr= "# # # histDUMP # # #"

saveMacro= "import readline; readline.write_history_file('"+historyTmp+"'); \
    print '####>>>>>>>>>>'; print ''.join(filter(lambda lineP: \
    not lineP.strip().endswith('"+endMarkerStr+"'),  \
    open('"+historyTmp+"').readlines())[-50:])+'####<<<<<<<<<<'"+endMarkerStr

readline.parse_and_bind('tab: complete')
readline.parse_and_bind('\C-w: "'+saveMacro+'"')

def save_history(historyPath=historyPath, endMarkerStr=endMarkerStr):
    import readline
    readline.write_history_file(historyPath)
    # Now filter out those line containing the saveMacro
    lines= filter(lambda lineP, endMarkerStr=endMarkerStr:
                      not lineP.strip().endswith(endMarkerStr), open(historyPath).readlines())
    open(historyPath, 'w+').write(''.join(lines))

if os.path.exists(historyPath):
    readline.read_history_file(historyPath)

atexit.register(save_history)

del os, atexit, readline, rlcompleter, save_history, historyPath
del historyTmp, endMarkerStr, saveMacro

You will then get all the goodies that come with bash shell (up and down arrows navigating the history, ctrl-r for reverse search, etc....).

Your complete command history will be stored in a file located at: ~/.pyhistory.

I'm using this from ages and I never got a problem.

HTH!

Upvotes: 5

Related Questions