I'm trying to make windows service in python.
I have three source files: add_to_startup.py (adding my service to windows startup), run_as_a_service.py (runs my program as a service) and test.py (my program).
First i create .exe with pyinstaller:
pyinstaller -F --onefile --hidden-import=win32timezone run_as_a_service.py test.py add_to_startup.py
When i trying to start service error occurs:
Error 1053: The service did not respond in a timely fashion.
If i delete strings with test import and test.service() function, service works.
run_as_service.py:
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import sys
import time
import test
class AppServerSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "test"
_svc_display_name_ = "Test"
_svc_description_ = "test test"
def __init__(self,args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.hWaitStop = win32event.CreateEvent(None,0,0,None)
socket.setdefaulttimeout(60)
def SvcStop(self):
self.isAlive = False
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
self.isAlive = True
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
self.main()
def main(self):
while self.isAlive:
test.service()
time.sleep(5)
if __name__ == '__main__':
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(AppServerSvc)
servicemanager.StartServiceCtrlDispatcher()
else:
win32serviceutil.HandleCommandLine(AppServerSvc)
test.py:
import add_to_startup
def service():
print("Hello world")
Related
I am trying to run a python script as windows service, but when ever I try to start the service I get error saying the service terminated with the following service-specific error:
Incorrect function
Whenever I try to start the service from services.msc it gives warning as "Windows could not start the service on Local computer...". Please find below screenshot depicting the same:
When I try to start the service from services.msc
Please find below event log from windows:
Event log from Windows
Below is the details of event log from windows:
- <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
- <System>
<Provider Name="Service Control Manager" Guid="{555908d1-a6d7-4695-8e1e-26931d2012f4}" EventSourceName="Service Control Manager" />
<EventID Qualifiers="49152">7024</EventID>
<Version>0</Version>
<Level>2</Level>
<Task>0</Task>
<Opcode>0</Opcode>
<Keywords>0x8080000000000000</Keywords>
<TimeCreated SystemTime="2023-02-09T07:46:29.0325014Z" />
<EventRecordID>19429</EventRecordID>
<Correlation />
<Execution ProcessID="92" ThreadID="20564" />
<Channel>System</Channel>
<Computer>ROHIT-TPE480</Computer>
<Security />
</System>
- <EventData>
<Data Name="param1">File Scanner Service</Data>
<Data Name="param2">%%1</Data>
<Binary>460069006C0065005300630061006E006E0065007200530065007200760069006300650050007900740068006F006E000000</Binary>
</EventData>
</Event>
Please find the main.py file:
import time
from datetime import datetime
from loggingUtils import *
from pathlib import Path
from SMWinservice import SMWinservice
def writeToFile():
DIR = "C:\\Users\\lenovo\\OneDrive\\Desktop\\background\\log.txt"
while True:
with open(DIR,'a+') as file:
file.write(str(datetime.now()))
app_log = getLogger()
sys.stdout.write = app_log.info
sys.stderr.write = app_log.error
class WinServiceFileScanner (SMWinservice):
_svc_name_ = "FileScannerService"
_svc_display_name_ = "File Scanner Service"
_svc_description_ = "File Scanner Service in Python"
def start(self):
app_log.info("start main =======")
self.isrunning = True
def stop(self):
app_log.info("stop main =======")
self.isrunning = False
def main(self):
app_log.info("main main =======")
while self.isrunning:
writeToFile()
if __name__ == '__main__':
WinServiceFileScanner.parse_command_line()
Please find below service class:
import socket
import win32serviceutil
import servicemanager
import win32event
import win32service
import sys
from loggingUtils import *
app_log = getLogger()
sys.stdout.write = app_log.info
sys.stderr.write = app_log.error
class SMWinservice(win32serviceutil.ServiceFramework):
_svc_name_ = 'pythonService'
_svc_display_name_ = 'Python Service'
_svc_description_ = 'Python Service Description'
#classmethod
def parse_command_line(cls):
app_log.info("parse cmd line Service..........")
win32serviceutil.HandleCommandLine(cls)
def __init__(self, args):
app_log.info("init Service..........")
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
socket.setdefaulttimeout(60)
def SvcStop(self):
app_log.info("DoStop Service..........")
self.stop()
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
app_log.info("DoRun Service..........")
self.start()
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_, ''))
self.main()
def start(self):
app_log.info("Starting Service..........")
pass
def stop(self):
app_log.info("Stopping Service..........")
pass
def main(self):
app_log.info("Main Service..........")
pass
if __name__ == '__main__':
SMWinservice.parse_command_line()
I am using Windows 10 Home Edition with Intel(R) Core(TM) i5-8250U CPU processor
Can someone please guide what is going wrong here? Appreciate your help
I am facing some issue when I try to start a flask simple Hello World as a service on windows, I have tried diferent solutions, but any of them get the same windows error.
"O serviço não respondeu à requisição de início ou controle em tempo hábil".
The service did not respond to the start or control request in a timely manner.
import win32serviceutil
import win32service
import win32event
import win32evtlogutil
import servicemanager
import socket
import time
import logging
import os
import sys
sys.path.append(os.path.dirname(__name__))
from myapp import app
logging.basicConfig(
filename = r'c:\tmp\flask-service.log',
level = logging.DEBUG,
format = '[flaskapp] %(levelname)-7.7s %(message)s'
)
class HelloFlaskSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "FlaskAppTest"
_svc_display_name_ = "FlaskApp Service"
def __init__(self, *args):
win32serviceutil.ServiceFramework.__init__(self, *args)
self.hWaitStop = win32event.CreateEvent(None,0,0,None)
socket.setdefaulttimeout(5)
self.stop_requested = False
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
self.ReportServiceStatus(win32service.SERVICE_STOPPED)
logging.info('Stopped service ...')
self.stop_requested = True
def SvcDoRun(self):
servicemanager.LogMsg(
servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,'')
)
self.main()
def main(self):
app.run(host="127.0.0.1", port=8000)
if __name__ == '__main__':
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(HelloFlaskSvc)
servicemanager.StartServiceCtrlDispatcher()
else:
win32serviceutil.HandleCommandLine(HelloFlaskSvc)
and this is myapp.py
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello():
return 'Hello World!'
and this is the actual command I am using to make the executable
pyinstaller --onefile --hidden-import=win32timezone win32_service.py
I have this which runs a python script as windows service and its working perfectly, is there a way to separate it into 2 files: one which is the main script in which the work is done and calls the serviceframework file and the other is the serviceframework
I tried doing it but it doesn't seem to work for me, any help would be much appreciated
import time
import win32serviceutil # ServiceFramework and commandline helper
import win32service # Events
import servicemanager # Simple setup and logging
class MyService:
"""Silly little application stub"""
def stop(self):
"""Stop the service"""
self.running = False
def run(self):
"""Main service loop. This is where work is done!"""
self.running = True
while self.running:
time.sleep(10) # Important work
servicemanager.LogInfoMsg("Service running...")
class MyServiceFramework(win32serviceutil.ServiceFramework):
_svc_name_ = 'MyService'
_svc_display_name_ = 'My Service display name'
def SvcStop(self):
"""Stop the service"""
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
self.service_impl.stop()
self.ReportServiceStatus(win32service.SERVICE_STOPPED)
def SvcDoRun(self):
"""Start the service; does not return until stopped"""
self.ReportServiceStatus(win32service.SERVICE_START_PENDING)
self.service_impl = MyService()
self.ReportServiceStatus(win32service.SERVICE_RUNNING)
# Run the service
self.service_impl.run()
def init():
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(MyServiceFramework)
servicemanager.StartServiceCtrlDispatcher()
else:
win32serviceutil.HandleCommandLine(MyServiceFramework)
if __name__ == '__main__':
init()
I have created a test service file in pyhton:
import datetime
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
def writetofile():
DIR = "D:\prog\log.txt"
while True:
with open(DIR, 'a+') as file:
file.write(str(datetime.now()))
class AppServerSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "TESTEST"
_svc_display_name_ = "TESTEST"
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):
writetofile()
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(AppServerSvc)
I've also installed it but when I want to start in win services it stops every time with 1053 error.
I have tried to overwrite the register file (ServicesPipeTimeout) not worked. I set it up 180000 and nothing. My program ran for a while then stopped again.
I've installed everthing in cmd as admin (pip install pywin32), not worked.
And I've installed the service too in cmd (python main.py install) and I see it, but thats all. I cant start it, cant delete it cant do anything with it.
If I try to do this it doesn't generate the warning:
Test.py install
Test.py start
Otherwise if I use pyinstaller:
pyinstaller -F --hidden-import=win32timezone Test.py
And then I try to do:
Test.exe install
Test.exe start
I see this warning in the event log:
A service process other than the one started by Service Control Manager connected when the TestService service started. Service Control Manager started process 5328 and connected process 1512.
Note that if the service is configured to start inside a debugger, this behavior is expected.
Script:
import servicemanager
import socket
import sys
import win32event
import win32service
import win32serviceutil
class TestService(win32serviceutil.ServiceFramework):
_svc_name_ = "TestService"
_svc_display_name_ = "Test Service"
_svc_description_ = "My service description"
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):
rc = None
while rc != win32event.WAIT_OBJECT_0:
with open('C:\\TestService.log', 'a') as f:
f.write('test service running...\n')
rc = win32event.WaitForSingleObject(self.hWaitStop, 5000)
if __name__ == '__main__':
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(TestService)
servicemanager.StartServiceCtrlDispatcher()
else:
win32serviceutil.HandleCommandLine(TestService)
How can I start the service without this warning appearing?
This is only a warning of windows complaining that the service fired two process.
This is the normal behaviour of pyinstaller executables. You should ignore this kind of warning.
See the docs