3

Is there a fast, convenient way to get all the code typed into the python interpreter so far? E.g., if I type this into the interpreter:

Steven$ python
Python 2.7.5 (default, Mar  9 2014, 22:15:05) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print "hi"
hi
>>> a = [1,2,3]
>>> for e in a:
...   print e
... 
1
2
3
>>> print "bye"
bye
>>> 

I would like to get these lines:

print "hi"
a = [1,2,3]
for e in a:
  print e
print "bye"
smci
  • 32,567
  • 20
  • 113
  • 146
Steven
  • 2,538
  • 3
  • 31
  • 40

2 Answers2

6

You can use the readline module.

Python 2.7.5 (default, Nov  3 2014, 14:26:24) 
[GCC 4.8.3 20140911 (Red Hat 4.8.3-7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "hi"
hi
>>> a = [1,2,3]
>>> for e in a:
...     print e
... 
1
2
3
>>> print "bye"
bye
>>> import readline
>>> readline.write_history_file('history.py')

File history.py will contain your history including the last 2 lines:

$ cat history.py
print "hi"
a = [1,2,3]
for e in a:
    print e
print "bye"
import readline
readline.write_history_file('history.py')
mhawke
  • 84,695
  • 9
  • 117
  • 138
  • This works, but for some reason spaces in the output file show up as "\040". Easy enough to fix, but do you know how to prevent this from happening in the first place? – Steven Mar 04 '15 at 01:55
  • This seems to be an OSX libedit thing. Sorry, I don't know of a simple preventative fix for it. You could write your own save function that iterates over the available history and replaces `'\040'` with space. – mhawke Mar 04 '15 at 03:06
  • Does `'\040'` show up when you reload the history file with `readline.read_history_file()`? – mhawke Mar 04 '15 at 03:07
  • Super easy - it just plain works. TNX – SDsolar Nov 20 '17 at 00:44
  • can you make it so it only gets this particular sessions history ? This printed 3 or 4 past executions of history. – John Sohn Sep 30 '21 at 13:40
0

The %history magic function should do it for you.

In [1]: l = [1,2,3]

In [2]: %history
l = [1,2,3]
%history

If you find you do this often consider using an ipython notebook.

dranxo
  • 3,348
  • 4
  • 35
  • 48