DaiBu DaiBu - 1 year ago 48
Linux Question

Python script is killed from within, but the process doesn't die

I'm trying to execute a python script using php with an exec command like this:

exec("python /address/to/script.py");

I don't need the script to run to completion, so after it does what I need, I call
from within it. Execution is passed back to the php script, which is great, however the python process is still running. I can see it in my server's process list. Is there more that's required to fully kill it?

Additional Info

  • The python script was written by a third party.

  • I know very little about python, just enough to add the

Answer Source

The script could still be executing some cleanup code, or you could be calling sys.exit() from a child process which will essentially be calling thread.exit(), leaving the parent process running.

Check that the sys.exit() call is in the main part of the script and that no error handling is interfering with the SystemExit exception, or alternatively you could try os._exit(). Also ensure that an ampersand (&) is not present within the command passed to exec() as this will cause the script to run as a background process.

Note that os._exit() is not favourable since it doesn't do any cleanup, and essentially ends the process immediately.

Edit To end the script from within your try block you could do something like this:

    # Existing Code
except SysExit:
    sys.exit() # quit the main thread
    # Existing error handling