Python implements the Windows Service service program
Win32serviceutil. Serviceframework is a well-packaged Windows service framework that is implemented by inheriting it.
- Through the Svcdorun method, the service starts and runs the business code within the service.
- Stop the service through the Svcstop method.
The winpollmanager.py code is as follows:
Import win32serviceutilimport win32serviceimport win32eventimport winerrorimport servicemanagerimport timeimport Sysimport osclass Winpollmanager (win32serviceutil. Serviceframework): "" "#1. Installing the service Python winpollmanager.py install #2. Let the service automatically start Python winpollmanager.py--start Up auto install #3. Start the service Python winpollmanager.py start #4. Restart the service Python winpollmanager.py restart #5. Stop Service Python winpollmanager.py stop #6. Remove/Uninstall service Python winpollmanager.py remove "" "_svc_name_ =" Py_agent_poll_manag ER "# service name _svc_display_name_ =" Py_agent_poll_manager "# Service is displayed in Windows system name _svc_description_ =" Python windows mo Description of the Nitor Agent "# Service def __init__ (self, args): Win32serviceutil. Serviceframework.__init__ (self, args) Self.hwaitstop = win32event. CreateEvent (None, 0, 0, none) self.isalive = True SELF._POLL_INTVL = def svcdorun (self): while Self.isAlive:print ' Monitor testing ' time.sleep (SELF._POLL_INTVL) def svcstop (self): self. Reportservicestatus (Win32service. service_stop_pending) win32event. SetEvent (self.hwaitstop) self.isalive = falseif __name__ = = ' __main__ ': If Len (sys.argv) = = 1:try: Evtsrc_dll = Os.path.abspath (servicemanager.__file__) ServiceManager. Preparetohostsingle (Winpollmanager) ServiceManager. Initialize (' Winpollmanager ', Evtsrc_dll) ServiceManager. StartServiceCtrlDispatcher () except Win32service.error, details:if details[0] = = Winerror. ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:win32serviceutil.usage () Else:win32serviceutil. Handlecommandline (Winpollmanager) # The arguments in parentheses can be changed to other names, but must match the class name;
Packaging EXE files
#-*-Coding:utf-8-*-"" "Pip Install pyinstallerpyinstaller-f-w winpollmanager.py" "" from pyinstaller.__main__ import ru nif __name__ = = ' __main__ ': params = [' winpollmanager.py ', '-f ', '-C ', '--icon=favicon.ico '] run (params)
Build exe file in dist directory after package success
Execution mode
- Installation Services WinPollManager.exe Install
- Service Auto-start WinPollManager.exe--startup Auto Install
- Start the service WinPollManager.exe Start
- Restart Service WinPollManager.exe Restart
- Stop Service WinPollManager.exe Stop
- Delete/Uninstall service WinPollManager.exe Remove
Reference article:
Http://zhangweide.cn/archive/2013/windows-service-example-using-pyinstaller.html
Http://www.cnblogs.com/dcb3688/p/4496934.html
http://blog.csdn.net/dysj4099/article/details/21896085
Python implements the Windows Service service program