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 ?
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.
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 .
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.
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).
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With