Loading and saving sessions and listing all variables

Loading and saving sessions and listing all variables

EXAMPLES:

We reset the current session, then define a rational number 2/3, and verify that it is listed as a newly defined variable:

sage: reset()
sage: w = 2/3; w
2/3
sage: show_identifiers()
['w']

We next save this session. We are using a file in SAGE_TMP. We do this for testing only — please do not do this, when you want to save your session permanently, since SAGE_TMP will be removed when leaving Sage!

sage: save_session(os.path.join(SAGE_TMP, 'session'))

This saves a dictionary with w as one of the keys:

sage: z = load(os.path.join(SAGE_TMP, 'session'))
sage: z.keys()
['w']
sage: z['w']
2/3

Next we reset the session, verify this, and load the session back.:

sage: reset()
sage: show_identifiers()
[]
sage: load_session(os.path.join(SAGE_TMP, 'session'))

Indeed w is now defined again.:

sage: show_identifiers()
['w']
sage: w
2/3

It is not needed to clean up the file created in the above code, since it resides in the directory SAGE_TMP.

AUTHOR:

  • William Stein
sage.misc.session.attach(*files)

Attach a file or files to a running instance of Sage and also load that file.

USAGE:

attach file1 ... - space-separated list of .py, .pyx, and .sage files, or attach('file1', 'file2') - filenames as strings, given as arguments to attach().

load() is the same as attach(), but doesn’t automatically reload a file when it changes.

Note

In addition to attach('foo.sage'), from the sage prompt you can also just type attach "foo.sage". However this second common usage is not part of the Python language.

EFFECT:

Each file is read in and added to an internal list of watched files. The meaning of reading in a file depends on the file type:

  • .py files are read in with no preparsing (so, e.g., 2^3 is 2 bit-xor 3);

  • .sage files are preparsed, then the result is read in;

  • .pyx files are not preparsed, but rather are compiled to a

    module m and then from m import * is executed.

The contents of the file are then loaded, which means they are read into the running Sage session. For example, if foo.sage contains x=5, after attaching foo.sage the variable x will be set to 5. Moreover, any time you change foo.sage, before you execute a command, the attached file will be re-read automatically (with no intervention on your part).

EXAMPLES:

You attach a file, e.g., foo.sage or foo.py or foo.pyx, to a running Sage session by typing:

sage: attach foo.sage   # or foo.py or foo.pyx or even a URL to such a file (not tested)

or:

sage: attach('foo.sage')  # not tested

Here we test attaching multiple files at once:

sage: sage.misc.reset.reset_attached()
sage: t1 = tmp_filename(ext='.py')
sage: open(t1,'w').write("print 'hello world'")
sage: t2 = tmp_filename(ext='.py')
sage: open(t2,'w').write("print 'hi there xxx'")
sage: attach(t1, t2)
hello world
hi there xxx
sage: set(attached_files()) == set([t1,t2])
True

See also

  • attached_files() returns a list of all currently attached files.
  • detach() instructs Sage to remove a file from the internal list of watched files.
  • load_attach_path() allows you to get or modify the current search path for loading and attaching files.
sage.misc.session.init(state=None)

Initialize some dictionaries needed by the show_identifiers(), save_session(), and load_session() functions.

INPUT:

  • state – a dictionary or None; if None the locals() of the caller is used.

EXAMPLES:

sage: reset()
sage: w = 10
sage: show_identifiers()
['w']

When we call init() below it reinitializes the internal table, so the w we just defined doesn’t count as a new identifier:

sage: sage.misc.session.init()
sage: show_identifiers()
[]
sage.misc.session.load_session(name='sage_session', verbose=False)

Load a saved session.

This merges in all variables from a previously saved session. It does not clear out the variables in the current sessions, unless they are overwritten. You can thus merge multiple sessions, and don’t necessarily loose all your current work when you use this command.

Note

In the Sage notebook the session name is searched for both in the current working cell and the DATA directory.

EXAMPLES:

sage: a = 5
sage: f = lambda x: x^2

For testing, we use a temporary file, that will be removed as soon as Sage is left. Of course, for permanently saving your session, you should choose a permanent file.

sage: tmp_f = tmp_filename()
sage: save_session(tmp_f)
sage: del a; del f
sage: load_session(tmp_f)
sage: print a
5

Note that f does not come back, since it is a function, hence couldn’t be saved:

sage: print f
Traceback (most recent call last):
...
NameError: name 'f' is not defined
sage.misc.session.save_session(name='sage_session', verbose=False)

Save all variables that can be saved to the given filename. The variables will be saved to a dictionary, which can be loaded using load(name) or load_session().

Note

  1. Function and anything else that can’t be pickled is not saved. This failure is silent unless you set verbose=True.

  2. In the Sage notebook the session is saved both to the current working cell and to the DATA directory.

  3. One can still make sessions that can’t be reloaded. E.g., define a class with:

    class Foo: pass
    

and make an instance with:

f = Foo()

Then save_session() followed by quit and load_session() fails. I doubt there is any good way to deal with this. Fortunately, one can simply re-evaluate the code to define Foo, and suddenly load_session() works fine.

INPUT:

  • name – string (default: ‘sage_session’) name of sobj to save the session to.
  • verbose – bool (default: False) if True, print info about why certain variables can’t be saved.

OUTPUT:

  • Creates a file and returns silently.

EXAMPLES:

For testing, we use a temporary file that will be removed as soon as Sage is left. Of course, for permanently saving your session, you should choose a permanent file.

sage: a = 5
sage: tmp_f = tmp_filename()
sage: save_session(tmp_f)
sage: del a
sage: load_session(tmp_f)
sage: print a
5

We illustrate what happens when one of the variables is a function:

sage: f = lambda x : x^2
sage: save_session(tmp_f)
sage: save_session(tmp_f, verbose=True)
Saving...
Not saving f: f is a function, method, class or type
...

Something similar happens for cython-defined functions:

sage: g = cython_lambda('double x', 'x*x + 1.5')
sage: save_session(tmp_f, verbose=True)
Not saving g: g is a function, method, class or type
...
sage.misc.session.show_identifiers(hidden=False)

Returns a list of all variable names that have been defined during this session. By default, this returns only those identifiers that don’t start with an underscore.

INPUT:

  • hidden – bool (Default: False); If True, also return identifiers that start with an underscore.

OUTPUT:

A list of variable names

EXAMPLES:

We reset the state of all variables, and see that none are defined:

sage: reset()
sage: show_identifiers()
[]

We then define two variables, one which overwrites the default factor function; both are shown by show_identifiers():

sage: a = 10
sage: factor = 20
sage: show_identifiers()
['a', 'factor']

To get the actual value of a variable from the list, use the globals() function.:

sage: globals()['factor']
20

By default show_identifiers() only returns variables that don’t start with an underscore. There is an option hidden that allows one to list those as well:

sage: _hello = 10
sage: show_identifiers()
['a', 'factor']
sage: '_hello' in show_identifiers(hidden=True)
True

Many of the hidden variables are part of the IPython command history, at least in command line mode.:

sage: show_identifiers(hidden=True)        # random output
['__', '_i', '_6', '_4', '_3', '_1', '_ii', '__doc__', '__builtins__', '___', '_9', '__name__', '_', 'a', '_i12', '_i14', 'factor', '__file__', '_hello', '_i13', '_i11', '_i10', '_i15', '_i5', '_13', '_10', '_iii', '_i9', '_i8', '_i7', '_i6', '_i4', '_i3', '_i2', '_i1', '_init_cmdline', '_14']

Previous topic

Determination of programs for viewing web pages, etc.

Next topic

Installing and using SageTeX

This Page