Cannot Call Python script from PHP

by Lee Morgan   Last Updated January 14, 2018 12:26 PM

I am trying to call a python script from PHP but not having any luck. I have searched for hours but found nothing. The python script is running just fine when I call it from the command line(connected to a relay switch, just runs through them, turning them on and off) and it works just fine. However, I can't seem to figure out how to get it to run from PHP. I am very new to PHP but here is what I am using:

<!doctype html>
    <meta charset="UTF-8"/>

        exec("sudo python /home/pi/Desktop/");

<form method="post">
    <button name="switch">Switch</button>


What am I doing wrong? I can't seem to find an answer anywhere that will make it work. The PHP is displaying the button just fine, but it does nothing when I click it.

Tags : php python

Answers 2

shell_exec — Execute command via shell and return the complete output as a string . reference

      $c=escapeshellcmd("sudo python /home/pi/Desktop/");
      echo $res; // returns result to display

in your script,output is not printed that may seem to not working

               $s=exec("sudo python /home/pi/Desktop/");
           echo "$s";        


add full path of interpreter in the first line of python script . if you have installed more than one python version

$s=exec("sudo -u /home/pi/Desktop/"); this gives permission to python file

first of all make python file executable with chmod +x /path/to/

jasinth premkumar
jasinth premkumar
January 13, 2018 13:02 PM

Please make sure that the www user has the permission to execute your python script.

and then you should check if the system could find the PATH of the python libraries that you import in your python code.

I have the same experience with you, and I fixed the problem by checking the apache2 error_log, you'd better try, The error_log will tell what the real problem is !

cd /var/log/apache2
sudo more error.log

chmod 777 test.php
chmod 777

Good luck!

bioinfo cheung
bioinfo cheung
January 13, 2018 13:20 PM

Related Questions

Images dimensions error in python

Updated February 24, 2018 05:26 AM

How to test Python 3.4 asyncio code?

Updated July 28, 2017 22:26 PM

Setting a class __name__ declaratively

Updated April 11, 2018 18:26 PM