Say you have a class like this:
class MyClass:
def __init__(self, var1):
self.var = var1
....
This class, in python, works only when you assign a value:
x = MyClass("Hi")
So basically, my question is whether I can send a variable from php to execute a python class, and return its output (it's string) and continue to execute my php code?
Any suggestions?
SOLUTION
in php:
$var = "something";
$result = exec("python fileName.py .$var")
in python:
import sys
sys.argv[0] # this is the file name
sys.argv[1] # this is the variable passed from php
-
[Similar question][1] [1]: stackoverflow.com/questions/166944/calling-python-in-phpNitish– Nitish2011年08月12日 13:59:49 +00:00Commented Aug 12, 2011 at 13:59
-
I've already read that, in that question it's not talking about passing variables...Shaokan– Shaokan2011年08月12日 14:04:07 +00:00Commented Aug 12, 2011 at 14:04
4 Answers 4
First of all, create a file containing the python-script you want to execute, including (or loading) the class and x = MyClass("Hi")
Now, use the following line to get the result:
$result = exec('python yourscript.py');
3 Comments
argv?). You can execute it from PHP like this: ... exec('python yourscript.py ' + $yourVariable);Try with the Python PECL package:
This extension allows the Python interpreter to be embedded inside of PHP, allowing for the instantiate and manipulation of Python objects from within PHP.
1 Comment
I managed to make simple function PY() for PHP which allows you virtually inlude python code to your PHP script. You may pass as well some input variables to python process. You cannot get any data back, but I believe that could be easily fixed :) Not ok for using at webhosting (potentionally unsafe, system() call), I created it for PHP-CLI but still may work fine..
<?php
function PY()
{
$p=func_get_args();
$code=array_pop($p);
if (count($p) % 2==1) return false;
$precode='';
for ($i=0;$i<count($p);$i+=2) $precode.=$p[$i]." = json.loads('".json_encode($p[$i+1])."')\n";
$pyt=tempnam('/tmp','pyt');
file_put_contents($pyt,"import json\n".$precode.$code);
system("python {$pyt}");
unlink($pyt);
}
//begin
echo "This is PHP code\n";
$r=array('hovinko','ruka',6);
$s=6;
PY('r',$r,'s',$s,<<<ENDPYTHON
print('This is python 3.4 code. Looks like included in PHP :)');
s=s+42
print(r,' : ',s)
ENDPYTHON
);
echo "This is PHP code again\n";
?>
Comments
You can just print the details/variables you want in the python file which will be bufferred to the $result variable in the php file and use echo $result in the php file to print the result back from the python file.
Here is the python modified code:
#!/usr/bin/python
import sys
print sys.argv[1] + sys.argv[0] # this is the variable passed from php