I want to know how I can stop my current python script when it is already running.
To be clear, I want to write it in my own python script. So the very first thing, in main method, it will check if my python script is already running or not. If it is running, I want to exit out with an error message.
Currently I am trying this code:
if os.system("ps ax | grep sample_python.py") == True:
print "fail"
exit(0)
else:
print "pass"
The above code looks like it is grepping the python name.. but it always go to else loop instead of going into the if loop and exit..
So for testing purposes, I run my script and on another terminal I run my script again. First script doesn't stop but 2nd python doesn't go into the if loop to print out error message.
How can I fix this?
Okay I found a dumb thing and I want to see if someone can help me go around it.. So my point was to kill the python that is just started if another python is currently running.. but the dumb thing is.. since I am running my python and running a checking coding inside of this python.. it will always exit.. because as soon as I start the python PID will be created and will be running...
So.. python starts -> pid created and running -> check if python is running -> yes python is running -> exit.
I want to see if there is a way to do python starts -> check if python is already running or not -> if it is running kill the current python not the one that was running.
A lockfile with PID of the running process is a more systematic way how to this. Program just checks at the start whether a PID file both exists and is locked (flock or lockf); if so, it means that another instance of this program is still running. If not, it creates (or rewrites) the PID file and locks it.
The flock/lockf lock has the advantage that operating system automatically removes the lock in case of program termination.
See here how to do this in Python: