Shaokan
Shaokan

Reputation: 7684

Execute python from php

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

Upvotes: 4

Views: 20542

Answers (4)

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

Upvotes: 0

Picmausek
Picmausek

Reputation: 39

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";
?>

Upvotes: 0

cutsoy
cutsoy

Reputation: 10251

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');

Upvotes: 7

corretge
corretge

Reputation: 1759

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.

http://pecl.php.net/package/python

Upvotes: 0

Related Questions