Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Communication between PHP and Python

Tags:

python

ajax

php

ipc

I'm trying to build a web interface for some python scripts. The thing is I have to use PHP (and not CGI) and some of the scripts I execute take quite some time to finish: 5-10 minutes. Is it possible for PHP to communicate with the scripts and display some sort of progress status? This should allow the user to use the webpage as the task runs and display some status in the meantime or just a message when it's done.

Currently using exec() and on completion I process the output. The server is running on a Windows machine, so pcntl_fork will not work.

LATER EDIT: Using another php script to feed the main page information using ajax doesn't seem to work because the server kills it (it reaches max execution time, and I don't really want to increase this unless necessary)

I was thinking about socket based communication but I don't see how is this useful in my case (some hints, maybe?

Thank you

like image 419
H. Stefan Avatar asked May 11 '11 14:05

H. Stefan


People also ask

How do I communicate with Python and PHP?

To call a Python file from within a PHP file, you need to call it using the shell_exec function.

Can PHP interact with Python?

Yes it will work, and how risky it is depends on how good your implementation is. This is perfectly acceptable if done correctly. I have successfully integrated PHP and C, when PHP was simply too slow to do certain niche tasks in real time (IIRC, PHP is 7 times slower than its C counterpart).

Can I run PHP and Python on same server?

Absolutely possible, as a matter of fact have you heard of PiP? I have even called Python without PiP and echo out lines in an HTML table before. Works like a charm. Save this answer.


2 Answers

You could use a queuing service like Gearman, with a client in PHP and a worker in Python or vice versa.

Someone has created an example setup here.

https://github.com/dbaltas/gearman-python-worker

like image 152
Tim Avatar answered Oct 05 '22 21:10

Tim


You want inter-process communication. Sockets are the first thing that comes to mind; you'd need to set up a socket to listen for a connection (on the same machine) in PHP and set up a socket to connect to the listening socket in Python and send it its status.

Have a look at this socket programming overview from the Python documentation and the Python socket module's documentation (especially the examples at the end). I'm sure PHP has similar resources.

Once you've got an more specific idea of what you want to build and need help, feel free to ask a new question on StackOverflow (if it isn't already answered).

like image 41
Humphrey Bogart Avatar answered Oct 05 '22 22:10

Humphrey Bogart