I have my python script set to run from cron in Ubuntu Server. However it might take longer time to finish, before another cron event will try to start it. I would like to determine such case from script itself and if running then gracefully terminate it from python script.
Save your pid to a file; if the file already exists, check that the process that left its PID is still alive. (This is safer than trying to ensure you always remove the file: You can't). The full process goes like this:
Check if the checkpoint file exists. If it does not, write your PID into the file and go ahead with the computation.
If the file exists: Read the PID and check if the process is, in fact, still alive. The best way to do that is with "kill -0" (from python: os.kill), which doesn't bother the running process but fails if it does not exist. If the process is still running, exit. Otherwise, write your PID to the file etc.
There's a small chance of a race condition, but if your process is getting restarted at infrequent intervals, that should be entirely harmless: Your process could always quit in favor of a running process that exits a second later, so what does it matter if the running process manages to quit first?
How to determine if my python script is running?