tags:

views:

88

answers:

5

I've got a version of the A* algorithm that builds a graph of the UK road and cycle network in Python lists. It takes about 30 seconds to initialise, but once done can very quickly find the shortest route between any two vertices. The start and finish vertex ids are provided by PHP.

I'm trying to work out the best way of communicating between PHP and the Python program. I only want to do the initialisation phase when the Apache server starts, so my question is: How do I keep the python program alive and request routes from it via php? I have a GLAMP setup.

A: 

Check this question out: http://stackoverflow.com/questions/166944/calling-python-in-php

Also check out this extension: http://www.csh.rit.edu/~jon/projects/pip/

I don't know if you're hosting environment allows you to add new php extensions, but you get the idea.

Bryan Ross
+1  A: 

Easiest way that I can think of would be XMLRPC. Python makes it horribly easy to set up an XMLRPC server, and there's php_xmlrpc for bindings on the PHP side...

def calculate_path(v1, v2):
  return [v1, ..., v2]

from SimpleXMLRPCServer import SimpleXMLRPCServer
server = SimpleXMLRPCServer(('localhost', 9393))
server.register_function(calculate_path)
server.serve_forever()

and you're running and should be able to do an XMLRPC call for calculate_path on http://localhost:9393/ from your PHP app.

AKX
Thanks for all the solutions offered, but I went for this one in the end as it looked the simplest. However, it did take me quite a while to get the Pear module working with PHP5.3,- which I did by predefining function dl() {return false;}We've now stripped out most of the XMLRPC package to have a very lightweight version.
Simon Nuttall
A: 

I would make a "backend" server from your Python application. There are many ways to call into the Python application:

This avoids any startup penalty for the Python application.

Yann Ramin
A: 

One fast possibility might be sharing a Memcache bucket between the PHP and the Python instance. I have no idea how to do this, but I know from other questions that it is possible.

Pekka
A: 

You could do something as simple as a REST web server in Python using web.py:

http://webpy.org/

and then call that via PHP, should make the whole task super simple.

See this for more info:

http://johnpaulett.com/2008/09/20/getting-restful-with-webpy/

Jon