Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

python - Save session in IPython like in MATLAB?

It would be useful to save the session variables which could be loaded easily into memory at a later stage.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
In [23]: %logstart /tmp/session.log
Activating auto-logging. Current session state plus future input saved.
Filename       : /tmp/session.log
Mode           : backup
Output logging : False
Raw input log  : False
Timestamping   : False
State          : active

In [24]: x = 1

In [25]: %logstop

In [26]: quit()
Do you really want to exit ([y]/n)? y

Then we can restore the session with:

% ipython -log /tmp/session.log 
Activating auto-logging. Current session state plus future input saved.
Filename       : ipython_log.py
...

In [1]: x
Out[1]: 1

For more on "Session logging and restoring" see the docs.

Note that this merely stores the commands run by IPython. It does not save the state of the IPython session. Restoring the session requires re-execution of the commands.


If you set the PYTHONSTARTUP environment variable to point at a file called, say, startup.py:

PYTHONSTARTUP=/path/to/startup.py

then put the following in /path/to/startup.py:

try:
    # https://stackoverflow.com/a/5377051/190597 (Tom Dunham)
    __IPYTHON__
except NameError:
    pass
else:
    # https://stackoverflow.com/a/15898875/190597 (user2261139)
    from IPython import get_ipython
    ipython = get_ipython()
    ipython.magic("%logstart /tmp/session.log")

then IPython will call %logstart automatically whenever you start an interactive session.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...