Today we will introduce some application tips on running Python on windows service. I believe that anyone who has used the Python programming language will find that this powerful and easy-to-use programming language can help us easily implement many functional requirements.
- Import wmi
- Import OS
- C = wmi. WMI ()
- Watcher = c. Win32_PowerManagementEvent.watch_for
(EventType = 7) # monitor the standby event;
- While True:
- OS. system ("kdlj. vbs") # Run the "connect to broadband" program,
The vbs code of the old brother was used here;
- Watcher ()
Because the windows service has been running Python console windows, it seems a bit inconvenient. So I thought that if I could run it in windows service, it would be like other programs in windows service Manager.
Finally, I found the related introduction in the book "Python Programming On Win32" by Mark Hammond), which contains a simple template that puts the program code in the corresponding position:
- # SmallestService. py
- #
- # A sample demonstrating the smallest possible service written in Python.
- Import win32serviceutil
- Import win32service
- Import win32event
- Class SmallestPythonService (win32serviceutil. ServiceFramework ):
- _ Svc_name _ = "SmallestPythonService"
- _ Svc_display_name _ = "The smallest possible Python Service"
- Def _ init _ (self, args ):
- Win32serviceutil. ServiceFramework. _ init _ (self, args)
- # Create an event which we will use to wait on.
- # The "service stop" request will set this event.
- Self. hWaitStop = win32event. CreateEvent (None, 0, 0, None)
- Def SvcStop (self ):
- # Before we do anything, tell the SCM we are starting the stop process.
- Self. ReportServiceStatus (win32service. SERVICE_STOP_PENDING)
- # And set my event.
- Win32event. SetEvent (self. hWaitStop)
- Def SvcDoRun (self ):
- # Put your program code here.
- Win32event. WaitForSingleObject (self. hWaitStop, win32event. INFINITE)
- If _ name __= = '_ main __':
- Win32serviceutil. HandleCommandLine (SmallestPythonService)
- # The name in the brackets can be changed to another name, which must be the same as the class name;
Next, just install the service and run SmallestService. py install in cmd. In this way, you can find a Service named "The smallest possible Python Service" in The windows Service manager. If it is set to automatic start, it will automatically start and run in The background. ,)
However, even if windows Firewall is enabled.