0

It's seems a fairly simple question but I didn't manage to correctly save my ipython session using magic "%save" If i use the magic "%paste" at any time during the session, saving the session results in this output :

get_ipython().magic(u'paste')

Of course, I would like the pasted code to be saved instead.

Any ideas?

kdopen
  • 8,032
  • 7
  • 44
  • 52
cyrilV
  • 1
  • What version of IPython? I remember this behavior from back when I was often forced to use %cpaste instead of %paste in various cases because of other bugs, but I don't remember seeing it recently... – abarnert Apr 30 '15 at 12:52

2 Answers2

1

I can reproduce this with version 3.1.0 of ipython on Ubuntu

$ ipython
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
Type "copyright", "credits" or "license" for more information.

IPython 3.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: paste
def f(x):
    return 2**x
## -- End pasted text --

In [2]: f(4)
Out[2]: 16

In [3]: history
paste
f(4)
history

In [4]: save ptest.py 1-3
The following commands were written to file `ptest.py`:
get_ipython().magic(u'paste ')
f(4)
get_ipython().magic(u'history ')
In [5]: cat ptest.py
# coding: utf-8
get_ipython().magic(u'paste ')
f(4)
get_ipython().magic(u'history ')

In [6]: 

But the help for %save states that

This function uses the same syntax as %history for input ranges, then saves the lines to the filename you specify.

and that's actually what is happening. It is only saving the commands you type at the prompt, and the command you entered was paste, which the magic converts to get_ipython().magic(u'paste ').

Interestingly, trying to edit the function I created with paste puts me in vi staring at the same magic command and not the pasted function.

While the first behavior may not be a bug (even if it's not particularly helpful), this editing behavior definitely seems like one.

kdopen
  • 8,032
  • 7
  • 44
  • 52
1

As kdopen's says, if you use %save

is only saving the commands you type at the prompt

If you want to record the input of %paste you could use %logstart, during your session, you can stop and start logging with: %logoff/%logon

Here is more info on how to use this command: logstart

When you want to restore your session remember to run ipython with: -i yourlogfile.py command line option. ie: ipython3 -i ipython_log.py

J.Serra
  • 1,208
  • 9
  • 11
  • It is worth mentioning that %logstart will save your current session so far ___from the start of the session___ - so you don't have to remember to do it before any %paste operations. – Steve Barnes Oct 09 '21 at 10:38