问题
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.
回答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.
回答2:
Here's what Sage does (see the file src/sage/all_cmdline.py
):
from sage.all import *
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.)
来源:https://stackoverflow.com/questions/24592346/how-to-properly-evaluate-sage-code-from-within-a-python-script