-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnio_winservice.py
97 lines (77 loc) · 2.92 KB
/
nio_winservice.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
""" NIO Windows Service
When run, this file creates an interface between a Windows operating
system and an installed nio instance. The installed Windows service will
start automatically.
See below for required configuration at the top of NIOWinService class.
"""
from signal import CTRL_BREAK_EVENT
import servicemanager
import subprocess
import win32service
import win32event
import win32api
import win32console
import win32serviceutil
class NIOWinService(win32serviceutil.ServiceFramework):
""" Configure the path to your nio project and `niod` executable.
Running `where niod` in a command prompt will return the path to the
installed exectuable.
"""
# CONFIGURATION
# Must include quotes and double backslashes
project_path = "C:\\Users\\<user>\\nio\\projects\\my_project"
niod_path = "C:\\Users\\<user>\\nio\\env\\Scripts\\niod.exe"
# END CONFIGURATION
# Do not edit anything below this line
name = 'nio_{}'.format(project_path.split('\\')[-1])
_svc_display_name_ = name
_svc_name_ = name
_svc_description_ = project_path
def __init__(self, *args):
win32serviceutil.ServiceFramework.__init__(self, *args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
self.process = None
def log(self, msg):
servicemanager.LogInfoMsg(str(msg))
def error(self, msg):
servicemanager.LogErrorMsg(str(msg))
def SvcDoRun(self):
self.log('Triggered ...')
self.ReportServiceStatus(win32service.SERVICE_START_PENDING)
try:
self.ReportServiceStatus(win32service.SERVICE_RUNNING)
self.log('Starting ...')
self.start()
win32event.WaitForSingleObject(
self.hWaitStop,
win32event.INFINITE)
self.log('Exit')
except Exception as e:
self.error('Exception starting: {}'.format(e))
self.SvcStop()
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
self.log('Stopping ...')
self.stop()
self.log('Stopped.')
win32event.SetEvent(self.hWaitStop)
self.ReportServiceStatus(win32service.SERVICE_STOPPED)
def start(self):
self.log('Launching nio process')
win32console.AllocConsole()
self.process = subprocess.Popen(
[self.niod_path],
cwd=self.project_path,
creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
def stop(self):
try:
self.log('Stopping nio process')
if self.process:
win32api.GenerateConsoleCtrlEvent(
CTRL_BREAK_EVENT,
self.process.pid)
self.log('CTRL_BREAK_EVENT sent')
except Exception as e:
self.error('Exception stopping: {}'.format(e))
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(NIOWinService)