#!/usr/bin/env pythonimportos,sys,time,errno,signalifos.name=='nt':importctypesdefkill(pid,logfn,tryhard=True):logfn('# Killing daemon process %d'%pid)PROCESS_TERMINATE=1handle=ctypes.windll.kernel32.OpenProcess(PROCESS_TERMINATE,False,pid)ctypes.windll.kernel32.TerminateProcess(handle,-1)ctypes.windll.kernel32.CloseHandle(handle)else:defkill(pid,logfn,tryhard=True):try:os.kill(pid,0)logfn('# Killing daemon process %d'%pid)os.kill(pid,signal.SIGTERM)iftryhard:foriinrange(10):time.sleep(0.05)os.kill(pid,0)else:time.sleep(0.1)os.kill(pid,0)logfn('# Daemon process %d is stuck - really killing it'%pid)os.kill(pid,signal.SIGKILL)exceptOSError,err:iferr.errno!=errno.ESRCH:raisedefkilldaemons(pidfile,tryhard=True,remove=False,logfn=None):ifnotlogfn:logfn=lambdas:s# Kill off any leftover daemon processestry:fp=open(pidfile)forlineinfp:try:pid=int(line)exceptValueError:continuekill(pid,logfn,tryhard)fp.close()ifremove:os.unlink(pidfile)exceptIOError:passif__name__=='__main__':path,=sys.argv[1:]killdaemons(path)