I finally realised that the Sage shell is a Python shell and that it's possible to run Sage inside a Python script. With this knowledge I was able to write a Python script that can execute Sage commands and uses sockets for inter-process communication.
I decided to write the script to act as much like running sage -c 'commmand'
as possible. I copied most of the code from sage/local/sage-eval
and paired it up with a Python socket example and ended with the following Python script:
import socket
import sys
from cStringIO import StringIO
from sage.all import *
from sage.calculus.predefined import x
from sage.misc.preparser import preparse
SHUTDOWN = False
HOST = 'localhost'
PORT = 8888
MAX_MSG_LENGTH = 102400
# Create socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print 'Socket created'
# Bind socket to localhost and port
try:
s.bind((HOST, PORT))
except socket.error , msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
# Start listening on socket
s.listen(10)
print 'Socket now listening'
# Loop listener for new connections
while not SHUTDOWN:
# Wait to accept a new client connection
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
# Receive message from client
msg = conn.recv(MAX_MSG_LENGTH)
if msg:
if msg == "stop":
SHUTDOWN = True
else:
parsed = preparse(msg)
if parsed.startswith('load') or parsed.startswith('attach'):
os.system('sage "' + os.path.join(os.getcwd(), parsed.split(None, 1)[1]) + '"')
else:
# Redirect stdout to my stdout to capture into a string
sys.stdout = mystdout = StringIO()
# Evalutate msg
try:
eval(compile(parsed,'<cmdline>','exec'))
result = mystdout.getvalue() # Get result from mystdout
except Exception as e:
result = "ERROR: " + str(type(e)) + " " + str(e)
# Restore stdout
sys.stdout = sys.__stdout__
# Send response to connected client
if result == "":
conn.sendall("Empty result, did you remember to print?")
else:
conn.sendall(result)
# Close client connection
conn.close()
# Close listener
s.close()
I saved the script to a file called sage-daemon.py
in my Sage root folder. The stop
message handler isn't really neccessary, but it's useful if anyone can "properly" daemonize the script (and also to avoid interrupting the script with CTRL+C, because that will leave the socket as in-use for a while after the script has been interrupted). See my other question http://ask.sagemath.org/question/2350... .
To run the script: sage -python sage-daemon.py
This will leave the Sage shell waiting for socket input.
Here's a PHP script I used to test the functionality with:
<?php
$socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname("tcp"));
if (!$socket) die("Could not create socket\n");
$connected = socket_connect($socket, "localhost", 8888);
if (!$connected) echo "Not connected\n";
else {
$msg = "print solve(5*x==3,x)";
$sent = socket_send($socket, $msg, strlen($msg), 0);
if (!$sent) echo "Error sending message\n";
else {
if ($msg != "stop"){
$response = socket_read($socket, 1024);
if (!$response) echo "Error receiving response\n";
else echo $response . "\n";
}
}
}
socket_close($socket);
If successfull this should print ... (more)
Related questions (including this one):