Python writes the Windows service and needs to use the PYWIN32 package.
Directly on the code:
#encoding =utf8 "Created on 2014-7-1@author:wangmengnan" Import Osimport sysimport Win32serviceutilimport Win32serviceimport win32eventclass Pythonservice (win32serviceutil. Serviceframework): #服务名 _svc_name_ = "Pythonservice" #服务显示名称 _svc_display_name_ = "Python Service Demo" #服务 Description _svc_description_ = "Python service demo." def __init__ (Self,args): Win32serviceutil. serviceframework.__init__ (Self,args) self.hwaitstop = win32event. CreateEvent (none,0,0,none) Self.logger = Self._getlogger () self.isalive = True def _getlogger (self): Import logging import OS import Inspect logger = Logging.getlogger (' [Pythonservice] ') This_file = Inspect.getfile (Inspect.currentframe ()) Dirpath = Os.path.abspath (Os.path.dirname (This_f ile)) handler = Loggint. Filehandler (Os.path.join (Dirpath, "Service.log")) formatter = logging. Formatter ('% (asctime) s% (name) -12s% (levelname) -8s% (Message) s ') Handler.setformatter (formatter) Logger.addhandler (handler) Logger.setlevel (loggin G.info) return logger def svcdorun (self): Import time Self.logger.error ("Svc do run ...") While Self.isAlive:self.logger.error ("I am alive.") Time.sleep (1) def svcstop (self): Self.logger.error ("Svc does stop ...") self. Reportservicestatus (Win32service. service_stop_pending) #设置事件 win32event. SetEvent (self.hwaitstop) self.isalive = falseif __name__ = = ' __main__ ': Win32serviceutil. Handlecommandline (Pythonservice)
after the program is written, you need to install the service, and start the operation, such as the following commands:
Installation Services:
Python service.py Install
to have the service start automatically:
Python service.py--startup Auto Install
Start the service:
Python service.py start
Restart Service:
Python service.py restart
Stop service:
Python service.py stop
Delete/Uninstall Service
Python service.py Remove
After you install and start the service, you can find our own services through the services, services and applications----computer--- ---the image is as follows:
Python writes automation to write a Windows service