14

I have some code written in PHP, but I have also developed a script written in Python. Is it possible to call this Python script from the PHP code?

If yes, how can I pass parameters to the Python script from the PHP?

I have tried to find an answer without any success.

Can someone give me a clue?

rrawat
  • 1,071
  • 1
  • 15
  • 29
André
  • 24,706
  • 43
  • 121
  • 178

4 Answers4

26

You use the system function: http://php.net/manual/en/function.system.php

Something like this:

$mystring = system('python myscript.py myargs', $retval);
Daren Thomas
  • 67,947
  • 40
  • 154
  • 200
  • 1
    what is supposed to be present in `retval` and `mystring`. Are they same or different, I am assuming that `retval` will contain what all is present on the console. Can you please help on understanding that also. – Krishna Oza Jun 17 '15 at 19:10
  • the confusion comes from the use of ret**val**. The documentation is also at fault for this as they name this return var, then declare it as retval also. but in the above example $retval is the status of execution, an integer. and $mystring is the last line of output from the script you just ran, a string. Hope that clears things up. – Nalaurien Jun 06 '17 at 00:17
  • The return code (`$retval` here) of an executable program is an integer. The convention is, `0` for no errors and anything else is an application-specific error code. – Daren Thomas Jun 07 '17 at 07:23
3

I managed to make simple function PY([parametress], code) for PHP. You may almost include python code to your PHP. You may pass as well some simple 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..

<?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";
?> 
Picmausek
  • 39
  • 1
1

You can try this:

python scripts:

 test.py:
        print "hello"

then php Scripts

index.php:
   $i =`python test.py`;
   echo $i;
GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

Yes you can simply use exec() to call python program in php. simple sample program i have included here.

$pyscript = 'G:\wamp\www\ll\test.py';
$python = 'C:\\Python27\\python.exe';

$cmd='$pyscript $python';

exec("$cmd", $output);

You should specify your python.exe path and your python file path.Its must needed in windows environment.

Coder
  • 23
  • 1
  • 9