简单的应用程序监听程序,若被监听的程序崩溃会自动重启,类似Unix/Linux命令screen
目的:为该死的Windows而作
运行环境:Python
source code:
#!/usr/bin/python
import psutil
import os
import threading
import time
# you case applictions
processs = {
"game_server_d.exe": "D:\\ghoul_app\\game_server\\",
}
# watch interval(s)
interval = 2
def recordLog(log):
filename = "watch.log"
with open(filename, "a") as fp:
print(log)
fp.write(log)
fp.write("\n")
def isRunning(path, process_name):
try:
pids = psutil.pids()
for pid in pids:
p = psutil.Process(pid)
# print("pid-%d, pname-%s" % (pid, p.name()))
try:
if p.name() == process_name and p.cwd() == path:
return True
except psutil.AccessDenied as id:
continue
except psutil.NoSuchProcess as identifier:
print(identifier.msg)
return False
return False
def restart(path):
if len(path) > 0:
os.system(path)
def onTick():
for k, path in processs.iteritems():
if not isRunning(path, k):
fullPath = path + k
log = str("[%s] restart %s" % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), fullPath))
recordLog(log)
old_path = os.getcwd()
os.chdir(path)
restart(fullPath)
os.chdir(old_path)
# repeat
global timer
timer = threading.Timer(interval, onTick)
timer.start()
if __name__ == "__main__":
for k, v in processs.iteritems():
recordLog("watching appliction: %s" % (v + k))
timer = threading.Timer(interval, onTick)
timer.start()