How To Turn A Python Script Into A Windows Service
Hullo guys, today'southward post is just for the ones of you that work with the "OS of the misoriented slashes": Microsoft Windows. :)
Have you ever had the demand of writing a Python script that could run in background as a Windows Service? In this post, you will learn how to practise it in less than x minutes, no jokes.
I will skip all the introduction about Windows Services, how convenient they could be, how much could be appreciated the fact that they can exist run in background even when the user is logged off etc… I mean, if you lot tin lawmaking in Python and you lot use Windows I bet you already know what a Windows Service is, don't yous?
So, first of all, let's start by installing the Python for Windows extensions:
c:test> pip install pywin32
Once you have done information technology, let'southward write this base of operations grade, your Windows service will be a subclass of this base class.
1 ''' 2 SMWinservice 3 by Davide Mastromatteo 4 5 Base class to create winservice in Python half-dozen ----------------------------------------- 7 8 Instructions: 9 10 1. Simply create a new class that inherits from this base class 11 2. Ascertain into the new grade the variables 12 _svc_name_ = "nameOfWinservice" 13 _svc_display_name_ = "name of the Winservice that volition be displayed in scm" 14 _svc_description_ = "description of the Winservice that will exist displayed in scm" fifteen 3. Override the iii main methods: 16 def start(self) : if you lot need to practise something at the service initialization. 17 A proficient idea is to put hither the inizialization of the running condition xviii def terminate(self) : if you demand to do something simply before the service is stopped. 19 A good idea is to put hither the invalidation of the running condition 20 def primary(self) : your actual run loop. Only create a loop based on your running condition 21 4. Define the entry indicate of your module calling the method "parse_command_line" of the new grade 22 5. Savour 23 ''' 24 25 import socket 26 27 import win32serviceutil 28 29 import servicemanager 30 import win32event 31 import win32service 32 33 34 class SMWinservice(win32serviceutil.ServiceFramework): 35 '''Base class to create winservice in Python''' 36 37 _svc_name_ = 'pythonService' 38 _svc_display_name_ = 'Python Service' 39 _svc_description_ = 'Python Service Description' 40 41 @classmethod 42 def parse_command_line(cls): 43 ''' 44 ClassMethod to parse the command line 45 ''' 46 win32serviceutil.HandleCommandLine(cls) 47 48 def __init__(cocky, args): 49 ''' 50 Constructor of the winservice 51 ''' 52 win32serviceutil.ServiceFramework.__init__(self, args) 53 self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) 54 socket.setdefaulttimeout(60) 55 56 def SvcStop(cocky): 57 ''' 58 Called when the service is asked to stop 59 ''' 60 cocky.stop() 61 self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) 62 win32event.SetEvent(self.hWaitStop) 63 64 def SvcDoRun(self): 65 ''' 66 Called when the service is asked to kickoff 67 ''' 68 self.beginning() 69 servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, 70 servicemanager.PYS_SERVICE_STARTED, 71 (self._svc_name_, '')) 72 self.primary() 73 74 def get-go(self): 75 ''' 76 Override to add logic earlier the first 77 eg. running condition 78 ''' 79 pass 80 81 def end(self): 82 ''' 83 Override to add together logic before the stop 84 eg. invalidating running status 85 ''' 86 pass 87 88 def principal(self): 89 ''' 90 Main course to be ovverridden to add logic 91 ''' 92 pass 93 94 # entry point of the module: copy and paste into the new module 95 # ensuring you are calling the "parse_command_line" of the new created class 96 if __name__ == '__main__': 97 SMWinservice.parse_command_line()
Permit's examine the class we take only introduced a little.
def SvcDoRun(self) : it's the method that will be called when the service is requested to start.
def SvcStop(cocky) : it's the method that volition be chosen when the service is requested to terminate.
def start(self) : it's a method that you will exist asked to override if you lot demand to do something when the service is starting (before started)
def finish(self) : it's the method that you will be asked to override if yous need to do something when the service is stopping (before stopped)
def primary(cocky) : it's the method that will incorporate the logic of your script, usually in a loop that keeps it alive until the service is stopped.
def parse_command_line(cls) : it's the method that handles the command line interface that you can use to install and update your windows service
Can you see how easy information technology is with pywin32 to interface with the arrangement to create a Windows Service? The last mention is for the following variables:
1svc_name = "PythonCornerExample" twosvc_display_name = "Python Corner's Winservice Example" 3svc_description = "That'due south a nifty winservice! :)"
These are just iii variables that incorporate the name of the service, the "friendly name" that volition exist used by Windows to display the name on the mmc panel and a brusque description of your service.
As always, enough talk, let'south code something useful!
Let's pretend that we want to create a Winservice that, when started, creates a random file on our C: drive every 5 seconds.
What? Do you remember it is stupid? Well, install it on your boss PC, set the destination folder as its user'due south desktop and you will alter your mind. :)
However, how tin you lot achieve this result? Super easy.
- Subclass the SMWinservice class we have just met.
- On the new course, override the three variables svc_name , svc_display_name and svc_description .
- Override the " start " method to gear up the running status. Setting a boolean variable will be enough for that.
- Override the " stop " method to invalidate the running condition when the service is requested to be stopped.
- Override the " principal " method to add the logic of creating a random file every 5 seconds
- Add together the call at the " parse_command_line " office to handle the command line interface.
The outcome should be something like this:
ane import fourth dimension ii import random three from pathlib import Path four from SMWinservice import SMWinservice 5 vi class PythonCornerExample(SMWinservice): vii _svc_name_ = "PythonCornerExample" viii _svc_display_name_ = "Python Corner's Winservice Example" 9 _svc_description_ = "That'southward a great winservice! :)" 10 xi def start(self): 12 self.isrunning = Truthful 13 xiv def stop(cocky): 15 self.isrunning = Faux sixteen 17 def main(self): 18 i = 0 19 while self.isrunning: 20 random.seed() 21 10 = random.randint(1, million) 22 Path(f 'c: {ten} .txt').touch() 23 time.slumber(5) 24 25 if __name__ == '__main__': 26 PythonCornerExample.parse_command_line()
That'southward it! At present it's time to install our newly created winservice. Just open a command prompt, navigate to your script directory and install the service with the command:
C:test> python PythonCornerExample.py install Installing service PythonCornerExample Service installed
In the future, if you desire to alter the code of your service, just modify it and reinstall the service with
C:test> python PythonCornerExample.py update Irresolute service configuration Service updated
Now, open the "Services" msc snap in
C:test> mmc Services.msc
locate your new PythonCornerExample winservice, and right click and choose properties. Here you tin can start your service and configure information technology at your will.
Now try to get-go your service and go to see your C: folder contents.
Can you meet all these files existence created to your C: binder? Yep, that's working!
But at present it's time to stop information technology! :) You can do it from the previous windows or just by using the command line
C:test> net end PythonCornerExample Il servizio Python Corner'southward Winservice Case sta per essere arrestato.. Servizio Python Corner's Winservice Example arrestato.
If something goes incorrect…
There are a couple of known problems that tin happen writing Windows Services in Python. If you have successfully installed the service but starting it yous go an error, follow this iter to troubleshoot your service:
- Check if Python is in your PATH variable. It MUST be there. To check this, simply open up a command prompt and try starting the python interpreter by typing "python". If it starts, y'all are ok.
- Be certain to take the file
C:\Program Files\Python36\Lib\site-packages\win32\pywintypes36.dll
(please note that "36" is the version of your Python installation). If y'all don't have this file, accept it fromC:\Program Files\Python36\Lib\site-packages\pywin32_system32\pywintypes36.dll
and copy it intoC:\Program Files\Python36\Lib\site-packages\win32
If yous still accept problems, try executing your Python script in debug mode. To try this with our previous example, open a terminal, navigate to the directory where the script resides and type
c:test> python PythonCornerExample.py debug
Ok, that'southward all for today, this was just a brief introduction to developing Windows Services with Python. Try it by yourself and … happy coding!
D.
Source: https://thepythoncorner.com/posts/2018-08-01-how-to-create-a-windows-service-in-python/
Posted by: shipleywatiod.blogspot.com
0 Response to "How To Turn A Python Script Into A Windows Service"
Post a Comment