How do you run a Python script as a service in Windows?
Yes you can. I do it using the pythoncom libraries that come included with ActivePython or can be installed with pywin32 (Python for Windows extensions).
This is a basic skeleton for a simple service:
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
class AppServerSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "TestService"
_svc_display_name_ = "Test Service"
def __init__(self,args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.hWaitStop = win32event.CreateEvent(None,0,0,None)
socket.setdefaulttimeout(60)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
self.main()
def main(self):
pass
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(AppServerSvc)
Your code would go in the main()
method—usually with some kind of infinite loop that might be interrupted by checking a flag, which you set in the SvcStop
method
Run Python script as a windows service
Just a few days back I have successfully sorted out my issue I just made some changes to my code and it started working properly. I am only posting these answers for someone like me who got this issue in the future he can easily sort it out.
This is the new code:
def WriteToFile():
while True:
file = open ( "C:\\file.txt" , "w" )
now = datetime.now()
now = now.strftime("%B %d, %y %H:%M:%S")
file.write(now)
class Pythonservice(win32serviceutil.ServiceFramework):
_svc_name_ = 'PC-Service'
_svc_display_name_ = 'PC-Service'
_svc_description_ = 'Freindly Service'
@classmethod
def parse_command_line(cls):
win32serviceutil.HandleCommandLine(cls)
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
socket.setdefaulttimeout(60)
def SvcStop(self):
self.stop()
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
self.start()
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_, ''))
self.main()
def start(self):
self.isrunning = True
def stop(self):
self.isrunning = False
def main(self):
WriteToFile()
if __name__ == '__main__':
Pythonservice.parse_command_line()
After these changes, I opened up a command prompt as administrator and type this command to install my service.
C:\wamp64\www\project\python\New folder>python testing.py install
I got the success message. After successful installation, I started my service using this command
C:\wamp64\www\project\python\New folder>python testing.py start
and service started successfully I confirmed from service manager as well whether my service is running or not and it was running after restarting my pc service was still in running state.
Run Python script with parameter as Windows Service
change last 2 lines with bellow code:
import servicemanager, sys
if __name__ == '__main__':
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(PythonCornerExample)
servicemanager.StartServiceCtrlDispatcher()
else:
PythonCornerExample.parse_command_line()
How to create windows service using Python
Anyone facing this issue, just copy pywintypes36.dll
from Python36\Lib\site-packages\pywin32_system32
to Python36\Lib\site-packages\win32
Helpful commands:
Install a service:
python app.py install
Uninstall a service:
python app.py remove
Start a service:
python app.py start
Update service:
python app.py update
Run python script as a service on Windows with an interface
I guess that I already had my answer, when I asked this question. So without writing a server/client interface, I have to live with my log-files. Acknowledgements for the guidance in the comments.
Related Topics
Find Unique Rows in Numpy.Array
How to Read a Text File into a String Variable and Strip Newlines
How to Get the Path and Name of the File That Is Currently Executing
What Does It Mean If a Python Object Is "Subscriptable" or Not
Understanding Repr( ) Function in Python
Convert String to Variable Name in Python
How to Plot Data from Multiple Two Column Text Files With Legends in Matplotlib
How to Format a Floating Number to Fixed Width in Python
How to Create a List of Random Numbers Without Duplicates
How to Chain the Movement of a Snake'S Body
How to List All Functions in a Module
How to Use Pickle to Save a Dict (Or Any Other Python Object)
Speed Up Millions of Regex Replacements in Python 3
How to Use the Apply() Function For a Single Column
Groupby Value Counts on the Dataframe Pandas
Updating Gui Elements in Multithreaded Pyqt