Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
511 views
in Technique[技术] by (71.8m points)

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) 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...