-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathpywatcher.py
69 lines (56 loc) · 2.23 KB
/
pywatcher.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#coding=utf-8
import os
import inspect
import win32serviceutil
import win32service
import win32event
class PythonService(win32serviceutil.ServiceFramework):
"""
Usage: 'python pywatcher.py install|remove|start|stop|restart'
"""
#服务名
_svc_name_ = "pyWatcher"
#服务显示名称
_svc_display_name_ = "Python Process Watcher"
#服务描述
_svc_description_ = "Python Process Watcher"
def __init__(self, args):
import pyini
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
this_file = inspect.getfile(inspect.currentframe())
self.startpath = os.path.abspath(os.path.dirname(this_file))
self.ini = pyini.Ini(os.path.join(self.startpath, 'watcher.ini'))
self.logger = self._getLogger()
self.isAlive = True
def _getLogger(self):
from logfile import RotatingFile
logger = RotatingFile(os.path.join(self.startpath, self.ini.server.get('log_to', 'pywatcher.log')),
maxBytes=self.ini.server.get('logfile_maxbytes', 50*1024*1024),
backupCount=self.ini.server.get('logfile_backups', 10))
return logger
def SvcDoRun(self):
import time
import subprocess
#from g_server import main
self.logger.info("started")
try:
self.sub = subprocess.Popen('python g_server.py',
stdout=self.logger,
stderr=self.logger, shell=True, cwd=self.startpath)
except Exception as e:
self.logger.exception(e)
while self.isAlive:
time.sleep(1)
# 等待服务被停止
#win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
subprocess.call(['taskkill', '/F', '/T', '/PID', str(self.sub.pid)])
self.logger.info("stopped")
def SvcStop(self):
self.logger.info("stopping....")
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
# 设置事件
win32event.SetEvent(self.hWaitStop)
self.isAlive = False
if __name__=='__main__':
win32serviceutil.HandleCommandLine(PythonService)