Steven
Steven

Reputation: 2558

Get code entered so far in Python interpreter session

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"

Upvotes: 3

Views: 2026

Answers (2)

mhawke
mhawke

Reputation: 87064

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')

Upvotes: 6

dranxo
dranxo

Reputation: 3388

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.

Upvotes: 0

Related Questions