Run python from php

Suppose you have a class:

class MyClass: def __init__(self, var1): self.var = var1 .... 

This class in python only works when assigning a value:

 x = MyClass("Hi") 

So basically, my question is, can I send a variable from php to execute a python class and return my output (this is a string) and continue to execute my php code?

Any suggestions?

Decision

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 
+4
source share
4 answers

First of all, create a file containing the python script you want to execute, including (or loading) the class and x = MyClass("Hi")

Now, to get the result, use the following line:

 $result = exec('python yourscript.py'); 
+7
source

Try with the PECL Python package:

This extension allows you to embed the Python interpreter inside PHP, allowing you to instantiate and manipulate Python objects from PHP.

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

0
source

I managed to create a simple PY () function for PHP that allows you to practically embed python code in your PHP script. You can also pass some input variables to the python process. You cannot return the data, but I believe that this can be easily eliminated :) It is not suitable for use in web hosting (potentially dangerous, system () call), I created it for PHP-CLI, but I can work fine anyway.

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

You can simply print the details / variables you want in the python file to be buffered into the $ result variable in the php file and use echo $ result in the php file to output the result from the python file.

Here is the modified python code:

 #!/usr/bin/python import sys print sys.argv[1] + sys.argv[0] # this is the variable passed from php 
0
source

All Articles