1

I have called a python script within my PHP page using the code below:

echo shell_exec("python object_detection_tutorial_cmsc265.py");

The python script generates image files in a loop until a certain condition is met. Example is the code below:

 while (True):
      cv2.imwrite('image' + str(loop) + '.png',image);
      if (not condition):
          break

When the HTML/PHP page is exited in the browser, I can see that the images are still increasing in number, that means the python is still executing. How will I stop the python script upon exiting PHP page?

4
  • 1
    that python could easily be done in php, wouldent that solve the problem? Commented May 29, 2018 at 6:32
  • @smith --> Actually it was a complex code, so I chose to represent it with a brief code. I have to call the python script in my php and not embed it in php since it was already made. I have no problem with that except when PHP page is terminated, the python continues executing. Commented May 29, 2018 at 6:42
  • 2
    The trouble is that without a more complex solution, you cannot know when the user is going to exit your page. What you could do would be to add a bit of javascript in your web page in order to repeatedly 'ping' an url associated with your running loop, and once you stopped being 'pinged', you exit the loop. But it is likely that a more thorough description of what you are trying to achieve would help. Commented May 29, 2018 at 6:42
  • @Faibbus --> Yeah I can use javascript. I just wanted to kill the python process. Commented May 29, 2018 at 6:44

1 Answer 1

2

Assuming your Python script is running in background, like this, you cannot.

If you want to handle this you will have to handle pid. What following is kind of dirty, well using any kind of shell_exec is dirty anyway, but keep this in mind.

What you could do:

  1. Make the Python script echo its pid at script startup
  2. Use exec PHP function over shell_exec to get only script's first output line
  3. Kill this pid before leaving your PHP script

Python

import os
print(os.getpid())

# your script

PHP

// code
$pid = intval(exec('python foo.py'))
exec("kill $pid")

Well, I'm not PHP developer, but google just told me it may be better to use posix_kill over exec("kill $pid").


Again, this is not clean code, it's hacky and depends a lot of the system.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.