Python: check script is not already running

Use bash to look for a process with the current script's name.

import commands
import os
import time
import sys
 
def stop_if_already_running():
	script_name = os.path.basename(__file__)
	l = commands.getstatusoutput("ps aux | grep -e '%s' | grep -v grep | awk '{print $2}'| awk '{print $2}'" % script_name)
	if l[1]:
		sys.exit(0);

To test, add

stop_if_already_running()
 
print "running normally"
while True:
    time.sleep(3)

and launch the script two times.

Feedback

Thank You. Its working.


FYI.. Small correction - awk '{print $2}' is appeared twice in the command
Prabhath
Oct 8, 2015
#1
Thanks.. Its working for me. Please can you explain awk {print $2} use in command pipe.
djsharma
Aug 28, 2017
#2