Save params between script runs in iPython console

2019-08-26 09:31发布

问题:

I want to find iPython console equivalent to the Spyder console command.

When I use Spyder app all my variables are saved between script runs. By that I don't only mean I can inspect the values after script finished running but that those values will be preserved within next script run.

Spyder console command (doesn't work in iPython console):
runfile('some_file.py', wdir='/some/project/folder')

There is a similar command in iPython console:
%run -i "some_script.py"

The problem is that this command deletes old values when new script starts executing.

Why is this important?

Let's say my script among other things builds some model which takes long(er) then I'm willing to wait (every time). In Spyder I can run it just the first time and then comment out this line of code and next time only rest of the code is run and model is pulled from working memory.

(yes I know I can save the model in pickle format etc. but that's totally beside the point)

EDIT:
This is awkward but for some reason I don't have any problems with -i flag anymore. So I'm able to get the desired functionality with it. Maybe it's because of newer version of Anaconda.

回答1:

You can save the entire session using dill (An extension of python pickle). So every end of your script you would save the current session.

import dill
dill.dump_session("temp.pkl")

And every start of the script you would load the previous session.

import dill
dill.load_session("temp.pkl")

This retains all variables in the session so you can just comment out variables you don't need to change.