How to use Sage as a Python library
Yes you can import Sage as a library in a Python script. One caveat is that you need to run that Python script using the version of Python that is bundled with Sage; currently Python 2.6.x. To import Sage, put the following in your Python script:
from sage.all import *
Then when you want to run your script, you need to invoke Sage with the option “-python” which would run your script using the Python that comes with Sage. For example, if Sage is in your PATH variable then you can do this:
sage -python /path/to/my/script.py
Another way is to write a Sage script and run that script using Sage itself. A Sage script has the file extension “.sage” and is more or less a Python script but uses Sage-specific functions and commands. You can then run that Sage script like so:
This will take care of loading the necessary environment variables and default imports for you.
Say you have a Python script called “my_script.py”. In a Sage session, you can load that script as follows:
sage: load "/path/to/my_script.py"
When writing code, use the command attach() within a Sage session to automatically reload the script containing the code every time you save your changes.