Run Python function with arguments using PHP

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. 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:
    print('lights turned on')
    print('No input received')

and to call it

python3 bath


$cmd = "python3 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.