My goal is to run different Python functions with different arguments on a click of a HTML(PHP) button. When i execute the command in the terminal everything works fine (lights turn on)
# terminal python3 -c 'from lights import *; lights.turn_on_group("bath")'
but when i try to run the same command in PHP there happens nothing (blank page).
# test.php $cmd = "python3 -c 'from lights import *; lights.turn_on_group("bath")'"; $command = escapeshellcmd($cmd); $output = shell_exec($command);
Anyone has an idea how to fix this?
Your problem is being caused due to the statement
escapeshellcmd($cmd), as explained here your command separator character is being escaped due to security reasons hence not being interpreted by shell, Now you are left with two options
Remove the statement or simply do not escape your command, in your case its safe because you are executing hard coded command not a command taken from user. so no need to escape it.
$cmd = "python3 -c 'from lights import *; lights.turn_on_group("bath")'"; $output = shell_exec($cmd);
Just in case if you are too much willing to implement standards and use that function then wrap your code into a single python script e.g.
myLights.py then call your script with arguments it will work because command separator will not be needed!
import sys from lights import * if len(sys.argv) > 1: lights.turn_on_group(sys.argv) print('lights turned on') else print('No input received')
and to call it
python3 myLights.py bath
$cmd = "python3 myLights.py bath"; $command = escapeshellcmd($cmd); #no special characters it will work $output = shell_exec($command);
I would suggest you using this method as you will get more customizations and options added in just single command line call with security layers active.