Skip to content Skip to sidebar Skip to footer

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:

Solution 1:

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.

Solution 2:

Here's what Sage does (see the file src/sage/all_cmdline.py):

from sage.allimport *
from sage.calculus.predefined import x

If you put these lines in your Python file, then integrate(x,x) will work. (In fact, sage.calculus.predefined just defines x using the var function from sage.symbolic.ring; this just calls SR.var, as suggested in the other answer. But if you want to really imitate Sage's initialization process, these two lines are what you need.)

Post a Comment for "How To Properly Evaluate Sage Code From Within A Python Script"