Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a Python Script from PHP?

Tags:

python

php

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?

like image 864
André Avatar asked Mar 31 '11 09:03

André


People also ask

Can we call Python script from PHP?

To call a Python file from within a PHP file, you need to call it using the shell_exec function.

Can you connect Python to PHP?

You can run a python script via php, and outputs on browser. Basically you have to call the python script this way: $command = "python /path/to/python_script.py 2>&1"; $pid = popen( $command,"r"); while( ! feof( $pid ) ) { echo fread($pid, 256); flush(); ob_flush(); usleep(100000); } pclose($pid);

Can I use Python in HTML?

The new PyScript project lets you embed Python programs directly in HTML pages and execute them within the browser without any server-based requirements.


2 Answers

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

Something like this:

$mystring = system('python myscript.py myargs', $retval);
like image 53
Daren Thomas Avatar answered Oct 04 '22 13:10

Daren Thomas


You can try this:

python scripts:

 test.py:
        print "hello"

then php Scripts

index.php:
   $i =`python test.py`;
   echo $i;
like image 24
Sapam Rajesh Singh Avatar answered Oct 04 '22 11:10

Sapam Rajesh Singh