Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

executing Python script in PHP and exchanging data between the two

Tags:

python

php

Is it possible to run a Python script within PHP and transferring variables from each other ?

I have a class that scraps websites for data in a certain global way. i want to make it go a lot more specific and already have pythons scripts specific to several website.

I am looking for a way to incorporate those inside my class.

Is safe and reliable data transfer between the two even possible ? if so how difficult it is to get something like that going ?

like image 806
Neta Meta Avatar asked Dec 27 '12 00:12

Neta Meta


People also ask

How do I pass data between two Python scripts?

you can use multiprocessing module to implement a Pipe between the two modules. Then you can start one of the modules as a Process and use the Pipe to communicate with it. The best part about using pipes is you can also pass python objects like dict,list through it.

How do you run a Python script from PHP and show output on the browser?

To run a Python script from PHP, we can use the shell_exec function. $command = escapeshellcmd('/usr/custom/test.py'); $output = shell_exec($command); echo $output; to call escapeshellcmd to escape the command string. Then we call shell_exec to run the $command .

How do I communicate with Python and PHP?

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.

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).


1 Answers

You can generally communicate between languages by using common language formats, and using stdin and stdout to communicate the data.

Example with PHP/Python using a shell argument to send the initial data via JSON

PHP:

// This is the data you want to pass to Python $data = array('as', 'df', 'gh');  // Execute the python script with the JSON data $result = shell_exec('python /path/to/myScript.py ' . escapeshellarg(json_encode($data)));  // Decode the result $resultData = json_decode($result, true);  // This will contain: array('status' => 'Yes!') var_dump($resultData); 

Python:

import sys, json  # Load the data that PHP sent us try:     data = json.loads(sys.argv[1]) except:     print "ERROR"     sys.exit(1)  # Generate some data to send to PHP result = {'status': 'Yes!'}  # Send it to stdout (to PHP) print json.dumps(result) 
like image 68
Tom van der Woerdt Avatar answered Sep 25 '22 04:09

Tom van der Woerdt