Skip to main content
Stack Overflow
  1. About
  2. For Teams

Return to Revisions

4 of 4
added 586 characters in body
jasinth premkumar
  • 1.4k
  • 1
  • 13
  • 23

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')
jasinth premkumar
  • 1.4k
  • 1
  • 13
  • 23

AltStyle によって変換されたページ (->オリジナル) /