Reputation: 2918
Could I pass a variable from a .php
script to Python
and vice versa?.
For example:
//myPHPScript.php
$hello = 'hello';
//myPythonScript.py
print(get the result from $hello variable found in myPHPScript.php)
Upvotes: 4
Views: 32890
Reputation: 98921
For scenarios where the variable being passed contains spaces.
PHP:
<?php
$who = "my name";
shell_exec("/path/to/python /path/to/script.py \"$who\" ");
PYTHON:
import sys
if len(sys.argv) > 1:
who = sys.argv[1]
Upvotes: 2
Reputation: 57408
Depends on how you invoke the Python script. If you do that via system()
for example, you can put it in the arguments:
$hello = 'world';
$result = shell_exec('/path/to/python /path/to/your/script.py ' . $hello);
and in Python:
import sys
who = sys.argv[1]
print "Hello %s" % who
Now $result
in PHP will contain "Hello world".
A more performant possibility, not always possible but worth considering, is a sort of "fastcgi approach"; your Python script is actually always running and accepts socket connections (e.g. using HTTPlib) on, say, port 8888. At that point you can connect from PHP using cURL to http://127.0.0.1:8888
and send structured data encoded in JSON (since Python has a JSON decoder; I'm not so sure about a PHP unserializer), and return information via the same path.
The Python script is now, to all intents and purposes, a web service. You can also deploy several different scripts under the same web service interface and choose which one will answer based on a fake URI sent in the request.
With this approach you need to check that the state between requests is properly isolated, i.e., requesting data processing on behalf of Peter won't result in data being returned that belong to Paul; or that all data being processed is insecure, that is, it requires no security or authentication.
One other advantage of this approach is caching - the python script stays alive between requests being made from PHP, and can return the same answer to a known question with no need of recalculating anything, if this is doable. There are caching frameworks for Python that are ready to plug in.
An additional advantage is that you can easily scale this approach by deploying the Python service on a different machine (not necessarily reachable from the wider Internet), or even several different machines.
Upvotes: 18
Reputation: 4362
Open a unix domain socket somewhere on the filesysytem. Somewhere like /var/run. Then have your processes read and write to it like a normal file. Boom. Bidirectional communication.
Upvotes: 0
Reputation: 7369
Some options:
Upvotes: 2