Gabriel wrote:

> so i was thinking php has  the "exec" comand that  executes a program
> and  gets  his  answer if sage  has some way to execute his function
> by a pseudo-tty interface will be great  like that:
> ./sage --40+8
> sage: 48

One way that I know of to allow a language to access SAGE is to use
the following simple SAGE server program:

====

#
# Alex Clemesha <[EMAIL PROTECTED]> 2007
# Modified by Ted Kosan to use the SAGE preparser and to accept
# multiple line input.
#
from twisted.web2 import resource
from twisted.web2 import http_headers
from twisted.web2 import http
from twisted.web2 import channel
from twisted.web2 import server

#from sage.interfaces import sage0

# SAGE libraries
import sage.interfaces.sage0

from   sage.misc.misc import word_wrap
import sage.misc.preparser
from   sage.misc.viewer     import browser
from   sage.structure.sage_object import load, SageObject

global sage0
sage0 = sage.interfaces.sage0.Sage()

HTML = """
<html>
<head>
<script type="text/javascript">

var axajObject = createRequestObject();

function createRequestObject() {
    var xmlhttp;
    try { xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); }
  catch(e) {
    try {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch(e) {
        xmlhttp=null;
    }
  }
  if(!xmlhttp&&typeof XMLHttpRequest!="undefined") {
    xmlhttp=new XMLHttpRequest();
  }
    return  xmlhttp;
}

function sendRequest(event) {
    var code = document.getElementById("code").value;
    if (code.length > 0 && event.keyCode == 13) {
        var ecode = encodeURIComponent(code);
        //alert(ecode)
        var req = "/eval?code=" + ecode;
        try{
            axajObject.open("POST", req, true);
            axajObject.setRequestHeader('Content-Type',  "text/html");
            axajObject.onreadystatechange = handleResponse;
            axajObject.send("");
        }
        catch(e){
            // caught an error
            alert('Request send failed.');
        }
        finally{}
    }
}

function handleResponse() {
    if(axajObject.readyState == 4){
        var response = axajObject.responseText;
        //alert(response);
        var code = document.getElementById("code").value;
        var res = "<p>Result of " + code + ":&nbsp;&nbsp;" + response + "</p>";
        document.getElementById("output").innerHTML = res;
    }
}
</script>

<style type="text/css">
    #container{text-align:center;width:550px;border:1px solid #387CAF}
    #output{text-align:center;font-size:14px;font-weight:bold}
</style>

</head>

<body>
    <div id="container">
        <h3>Simplest possible AJAX SAGE calculator.</h3>
        <p>Type in some valid SAGE code and hit enter.</p><br/><br/>
        Code:&nbsp;<input type="text" id="code" name="code"
onkeypress="sendRequest(event)"></label>&nbsp;
        <br/><br/>
        <span id="output"></span>
        <br/><br/><br/><br/>
        <h3>If you run SAGEIDE on the same machine that the simple server is
running on, SAGEIDE can be used to send requests to the server
too.</h3>
    </div>
</body>
</html>
"""

class Root(resource.Resource):
        addSlash = True

        def __init__(self):
                self.child_eval = EvalSomeSAGECode()

        def render(self, request):
                return http.Response(200, {'content-type':
http_headers.MimeType('text', 'html')}, HTML)

class EvalSomeSAGECode(resource.PostableResource):

    def render(self, request):
                code_to_eval = request.args.get('code')[0]
                print code_to_eval
                
                directory = '/tmp'
                
                try:

                    #code_to_eval = code_to_eval.replace('\\','')
                        s = sage.misc.preparser.preparse_file(code_to_eval, 
magic=False,
                                        do_time=True, ignore_prompts=True)
                        s = [x for x in s.split('\n') if len(x.split()) > 0 and 
\
                                x.lstrip()[0] != '#']   # remove all blank 
lines and comment lines

                        if len(s) > 0:
                                t = s[-1]
                                if len(t) > 0 and not ':' in t and \
                                                not t[0].isspace() and not 
t[:3] == '"""':
                                        t = t.replace("'","\\'")
                                        s[-1] = "exec compile('%s', '', 
'single')"%t
                
                        s = '\n'.join(s) + '\n'
                        
                
                        open('%s/_temp_.py'%directory, 'w').write(s)
                

                        result = 
sage0._eval_line('execfile("%s/_temp_.py")'%directory)

                    #o = word_wrap(o, ncols=numcols)
                        print result
                        return http.Response(200, {'content-type':
http_headers.MimeType('text', 'html')}, result)
                
                
                except (RuntimeError, TypeError), msg:
                        print "ERROR!!!", msg



if __name__ == "__main__":
        from twisted.internet import reactor
        site = server.Site(Root())
        factory = channel.HTTPFactory(site)
        reactor.listenTCP(8000, factory)
        print "\nOpen your browser to 'http://localhost:8000'\n"
        reactor.run()

====

Save this program (lets call it php_server.py), set the "/tmp" string
to a directory of your choice, and then execute the program as
follows:

sage php_server.py

You can then test the program by pointing a web browser to
"http://localhost:8000";.


import java.beans.PropertyChangeEvent
import java.beans.PropertyChangeListener
import java.io.ByteArrayInputStream
import java.net.URL as URL
import java.net.URI as URI
import java.net.URLEncoder as URLEncoder
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.xpath.XPath
import javax.xml.xpath.XPathConstants
import javax.xml.xpath.XPathExpression
import javax.xml.xpath.XPathFactory
import org.jdesktop.http.async.AsyncHttpRequest.ReadyState as ReadyState
import org.jdesktop.http.async.AsyncHttpRequest as AsyncHttpRequest
import org.w3c.dom.Document
import org.w3c.dom.NodeList
import org.jdesktop.http.async.XmlHttpRequest
import org.jdesktop.http.Method as Method
import java.io.ByteArrayOutputStream
import java.lang.System as System
import pickle

#System.out.println(buffer.getText(0,buffer.length))


clazz = 
jEdit.getPlugin("org.sageide.SAGEIDEPlugin").getPluginJAR().getClassLoader().loadClass("org.sageide.SAGEIDE",1)

class ReadyListener( java.beans.PropertyChangeListener ):
        def __init__(self, request):
                self.req = request
                self.response = None
                self.obj = None

        def propertyChange(self, evt ):
                if evt.getNewValue() == ReadyState.LOADED:
                        clazz.displayText.append("New------------------\n ")
                        
                        
                        
                        self.response = self.req.getResponseText()
                        #System.out.println(self.response)
                        
                        if self.response != None:
                        

                        clazz.displayText.append(self.response + "\n\n ")
                                        
                                
                        else:
                                clazz.displayText.append("No response from 
server\n\n ")
                                
                        
clazz.displayText.setCaretPosition(clazz.displayText.getDocument().getLength())


req = AsyncHttpRequest()
                
si = ReadyListener(req)
req.addReadyStateChangeListener( si )
try:
        code = URLEncoder.encode(buffer.getText(0,buffer.length),"UTF8")
        #code = "2^3"
        #uri = URI("http", None,"localhost", 8000, "/eval", "code="+code, None)
        uri = "http://localhost:8000/eval?code="+code
        req.open(Method.POST, uri, 1 )
        req.setRequestHeader("Content-Type",  "text/html")
        req.send("")
except Exception, e:
        print "exception",e

--~--~---------~--~----~------------~-------~--~----~
To post to this group, send email to sage-support@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sage-support
URLs: http://sage.math.washington.edu/sage/ and http://sage.scipy.org/sage/
-~----------~----~----~----~------~----~------~--~---

Reply via email to