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.
The name
x
is not imported byimport sage.all
. To define a variablex
, you need to issue avar
statement, like thusor, better,
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.Here's what Sage does (see the file
src/sage/all_cmdline.py
):If you put these lines in your Python file, then
integrate(x,x)
will work. (In fact,sage.calculus.predefined
just definesx
using thevar
function fromsage.symbolic.ring
; this just callsSR.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.)