I am trying to add a function to a script to check if it is already running. This is because the script will be started with a cronjob.
Here a stub of what i attempted for that function:
import psutil
import sys
import time
print(__file__)
def check_if_running():
# print('process_nb: ', len(list(psutil.process_iter())))
for i, q in enumerate(psutil.process_iter()):
n = q.name()
# print(i, n)
if 'python' in n:
print(i, n)
c = q.cmdline()
print(c)
if __file__ in c:
print('already running')
sys.exit()
else:
print('not yet running')
return
if __name__ == '__main__':
check_if_running()
while True:
time.sleep(3)
I run the script a first time, then a second in a separate shell. On the second time it should print 'already running' and exit, however it doesn't.
Can anyone help me figure out why ?
'python'to'Python', this worked fine for me.pythonin the name, either viasys.exit()orreturn. I'm not sure you want theelse: returnin there; you probably want the loop to keep running if it finds some other python process.__file__no ?