Search code examples
pythonsageevaluate

How to properly evaluate sage code from within a Python script


I've been trying to evaluate a simple "integrate(x,x)" statement from within Python, by following the Sage instructions for importing Sage into Python. Here's my entire script:

    #!/usr/bin/env sage -python

from sage.all import *
def main():
    integrate(x,x)
    pass
main()

When I try to run it from the command line, I get this error thrown:

NameError: global name 'x' is not defined

I've tried adding var(x) into the script, global x, tried replacing integrate(x,x) with sage.integrate(x,x), but I can't seem to get it to work, I always get an error thrown.

The command I'm using is ./sage -python /Applications/path_to/script.py

I can't seem to understand what I'm doing wrong here.

Edit: I have a feeling it has something to do with the way I've "imported" sage. I have my a folder, let's call it folder 1, and inside of folder 1 is the "sage" folder and the "script.py"

I am thinking this because typing "sage." doesn't bring up any autocomplete options.


Solution

  • The name x is not imported by import sage.all. To define a variable x, you need to issue a var statement, like thus

    var('x')
    integrate(x,x)
    

    or, better,

    x = SR.var('x')
    integrate(x,x)
    

    the second example does not automagically inject the name x in the global scope, so that you have to explicitly assign it to a variable.