How can I pass variable from PHP to Python?
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)
Solution 1:
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.
Solution 2:
Some options:
- let the PHP write its variable to a file using some format (e.g. JSON or something), let the python program read the file (but think about this: what happens when multiple processes try to read/write?)
- let PHP store its data in a database, and the python script read from the same db (db should handle concurrency)
- let one process call the other process, passing data via stdin/stdout (circumvents file)
- use some other form of Inter Process Communication suitable for your platform