5.1 Loading and Attaching Sage files

Next we illustrate how to load programs written in a separate file into Sage. Create a file called example.sage with the following content:

print "Hello World"
print 2^3

You can read in and execute example.sage file using the load command.

sage: load "example.sage"
Hello World
8

You can also attach a Sage file to a running session using the attach command:

sage: attach "example.sage"
Hello World
8
Now if you change example.sage and enter one blank line into Sage (i.e., hit ``return''), then the contents of example.sage will be automatically reloaded into Sage.

In particular, attach automatically reloads a file whenever it changes, which is handy when debugging code, whereas load only loads a file once.

When Sage loads example.sage it converts it to Python, which is then executed by the Python interpreter. This conversion is minimal; it mainly involves wrapping integer literals in ZZ(), floating point literals in RR(), replacing ^'s by **'s, and replacing e.g., R.2 by R.gen(2). The converted version of example.sage is contained in the same directory as example.sage and is called example.sage.py. This file contains the following code:

print "Hello World"
print ZZ(2)**ZZ(3)
Integer literals are wrapped and the ^ is replaced by a **. (In Python ^ means ``exclusive or'' and ** means ``exponentiation''.)

Note: This preparsing is implemented in sage/misc/interpreter.py.

You can paste multi-line indented code into Sage as long as there are newlines to make new blocks (this is not necessary in files). However, the best way to enter such code into Sage is to save it to a file and use attach, as described above.

See About this document... for information on suggesting changes.