# Using Sage in a Python CGI script

I am writing cgi scripts in python that use sage. I have been researching for weeks and even the python and sage websites say use: "from sage.all import *" in your python script, and have "#!/usr/bin/env sage -python" as the first line of the script.

Here is the exact quote from sagemath faq on what to do: " The following standalone Sage script factors integers, polynomials, etc:

#!/usr/bin/env sage -python

import sys
from sage.all import *

if len(sys.argv) != 2:
print "Usage: %s <n>"%sys.argv[0]
print "Outputs the prime factorization of n."
sys.exit(1)

print factor(sage_eval(sys.argv[1]))


In order to use this script, your SAGE_ROOT must be in your PATH."

I made the cgi file exactly as is, and put onto my web server (Apache running CentOS), with sage and python installed. When I try to run this file (named factor.cgi) through the bash terminal I do:

$./factor.cgi 2006 /usr/bin/env: sage -python: No such file or directory  Any help on what I should do to make this script work would be appreciated. edit retag close delete ## 2 answers Sort by » oldest newest most voted answered 2013-05-29 08:40:32 -0500 Unfortunately, Linux passes the entire rest of the shebang command line as a single argument to the shebang executable. Therefore, if you use "#!/usr/bin/env prog", then it's impossible to pass any arguments to prog. My solution was to change it to #!/usr/bin/env sage-python  and write a wrapper script called sage-python containing exec /home/sage/sage-5.7-linux-32bit-ubuntu_12.04.2_lts-i686-Linux/sage -python$@

more

The problem seems to be that sage isn't in your $PATH. You can use thsese instructions to add $SAGE_ROOT to your path. Another (easier, in some sense) solution is to make the first line of your script be

#!/path/to/your/sage-4.7.1/sage -python


and then the script will know explicitly which Sage installation to use.

more

Setting the path works, but that requires me to add a shell script to call this script. I tried your suggestion of putting #!path/to/sage -python as the first line instead and running it as ./factor.cgi 2006 and I get this now: ./factor.cgi: line 2: import: command not found ./factor.cgi: line 3: import: command not found ./factor.cgi: line 5: syntax error near unexpected token from' ./factor.cgi: line 5: from sage.all import *'  ( 2011-07-08 03:00:11 -0500 )edit
That's strange. Where is your Sage installed? Could you post your factor.cgi script on something like pastebin.com? My Sage is installed at "/opt/sage", so I'd put "#!/opt/sage/sage -python" at the top of my script.  ( 2011-07-08 23:35:57 -0500 )edit