#coding=utf-8
#myTools.py
import daemon
import fcntl
import time
import sys
import os
class myTools:
def __init__(self,vPwd,isSingle = True,fLog = None):
self.isSingle = isSingle
self.pid = os.getpid()
if(fLog == None):
self.fLog = "%s/%s" % (vPwd,self.getLogFile())
else:
self.fLog = fLog
try:
self.fs = open(self.fLog,'a+')
except Exception as e:
print("open file '%s' error:%s" % (self.fLog,str(e)))
def Log(self,s):
try:
self.fs.write("%s pid:%d %s\n" % (time.ctime(),self.pid,s))
self.fs.flush()
except Exception as e:
print("write file error:"+str(e))
def getLogFile(self,):
selfFile = sys.argv[0]
if(selfFile[-3:].upper() == ".PY"):
selfFile = selfFile[0:-3]
tmpStr = selfFile[::-1]#reverse string
slashPos = tmpStr.find("/")#find the 1st "/"
if(slashPos == -1):
slashPos = None
tmpStr = tmpStr[0:slashPos]
logFile = "%s.log" % tmpStr[::-1]
return logFile
def existsInstance(self,):
if(self.isSingle):
try:
fcntl.flock(self.fs.fileno(),fcntl.LOCK_EX | fcntl.LOCK_NB)
return False
except Exception as e:
#self.Log(str(e))
return True
else:
return False
def __del__(self,):
try:
self.fs.close()
except:
pass
if __name__ == "__main__":
vPwd = os.getcwd()
with daemon.DaemonContext():
tl = myTools(vPwd)
if(tl.existsInstance()):
tl.Log('script is exists and exit')
exit(0)
tl.Log('script is started to dong something')
time.sleep(20)
tl.Log('script is ended')