0

I have a mask detection python program. Whenever we run that, it keeps running continuously and keeps detecting (endless program). I have made a web portal to start off this python program on a button click event using php. Now the issue is that when i start off this program by shell_exec() , it starts. But php waits for the program to finish. Till the time program is running (from shell_exec() ), php just freezes, doesn't even load any other page.

So how to run cmd command from shell_exec() and not wait for it to finish executing?

CODE

$command = escapeshellcmd("start cmd /c python mask_detector.py " );
$output = shell_exec($command);

2 Answers2

0

This can be achieved in multiple ways, one relatively easy one I could think of is using PIPE and continuously reading in the results. If you

for example:

from subprocess import PIPE, run

cmd = [python3, "SCRIPTNAME.py" ...]
result = run(cmd, stdout=PIPE, stderr=PIPE, universal_newlines=True)

now you could redirect the standard output to a file as shown here (specially this post) depending on OS and Python version.

Now, you can read this file (or a copy of it) every x seconds and send it to PHP.

xtlc
  • 1,070
  • 1
  • 15
  • 41
0

I found and easy solution for my question on this blog https://subinsb.com/how-to-execute-command-without-waiting-for-it-to-finish-in-php/

Thanks to this genius

Solution given here is this function

function <span style="color: red;">bgExec</span>($cmd) {
 if(substr(php_uname(), 0, 7) == "Windows"){
  pclose(popen("start /B ". $cmd, "r")); 
 }else {
  exec($cmd . " > /dev/null &"); 
 }
}

I tried redirecting my stdout to null, but it didn't worked for me in Windows platform. Above function uses popen() and pclose() functions. That gets my job done.

pclose(popen("start cmd /c python demo.py", "r"));