0

There is some functionality written in python which I need to use in PHP. I need to pass parameters to python function and pass result(at least simple types: integer, float, tuple, etc.) back into php?. Can it be done?

djeendo
  • 317
  • 1
  • 3
  • 9
  • python & PHP are 2 different programming languages. You want a converter? – Raptor Jan 16 '13 at 07:06
  • 2
    Would you accept `yes` as an answer? :) Seriously though, some more context and background would be useful – Jon Clements Jan 16 '13 at 07:06
  • 2
    Actually, you can use the shell to execute other programs easily. The same way you would fire a shell script in PHP, you can call a Python program and get the return output value as long as it prints directly to stdout or you pass a special file stream handle. The question is, why? – Sudipta Chatterjee Jan 16 '13 at 07:09

2 Answers2

3

you can run any external script from php using exec

or

Create a web service to access. This would be the best method.

Venu
  • 7,243
  • 4
  • 39
  • 54
1

You should use XML-RPC (remote procedure calling). It's dead-simple to setup a Python-Server for this, and in PHP, go with http://php.net/manual/de/ref.xmlrpc.php .

E.g., as example (taken from the docs)

from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler

# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ('/RPC2',)

# Create server
server = SimpleXMLRPCServer(("localhost", 8000),
                            requestHandler=RequestHandler)
server.register_introspection_functions()

# Register pow() function; this will use the value of
# pow.__name__ as the name, which is just 'pow'.
server.register_function(pow)

# Register a function under a different name
def adder_function(x,y):
    return x + y
server.register_function(adder_function, 'add')

# Register an instance; all the methods of the instance are
# published as XML-RPC methods (in this case, just 'div').
class MyFuncs:
    def div(self, x, y):
        return x // y

server.register_instance(MyFuncs())

# Run the server's main loop
server.serve_forever()

sets up a fully working XML-RPC-server.

Then every method of MyFuncs is available for use from any programming language that supports XML-RPC, including PHP.

Thorsten Kranz
  • 12,492
  • 2
  • 39
  • 56