简体   繁体   中英

Cannot Call Python script from PHP

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>
<head>
    <meta charset="UTF-8"/>
</head>

<?php
    if(isset($_POST['switch'])){
        exec("sudo python /home/pi/Desktop/test.py");
    }
?>

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

</html>

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.

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

<?php
    if(isset($_POST['switch'])){
      $c=escapeshellcmd("sudo python /home/pi/Desktop/test.py");
      $res=shell_exec($c);
      echo $res; // returns result to display
    }
?>

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

    <?php
        if(isset($_POST['switch'])){
               $s=exec("sudo python /home/pi/Desktop/test.py");
           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/test.py"); this gives permission to python file

first of all make python file executable with chmod +x /path/to/python-script.py

EDIT:

from this post

You can't use sudo from a PHP script. Apache is running from an user (www-data generaly), so edit this file : /etc/sudoers

Then add this line :

www-data ALL=(ALL) NOPASSWD:ALL

Care ! this will authorize all functions to be called by a PHP script, you can adapt changing "ALL" by your script or Python command.

Then precise your user in your exec command :

<?php
exec('sudo -u www-data python /usr/lib/cgi-bin/script.py')

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 test.py

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM