Below is my shellscript:
& 'C:\files\service_file.exe' install
#Start the windows service
& 'C:\file\service_file.exe' start --env "D:\full_project\device\config\windows.env"
I used pyinstaller to create service_file.exe and 'start' arg is working fine but does not support env path if included
I get path not found error, even after giving the env.
below is my service_file.py
import os
import win32serviceutil
import win32service
import servicemanager
import argparse
class MyService:
def stop(self):
self.running = False
def run(self):
application_path = os.path.dirname(sys.executable)
os.chdir(application_path)
def load_env(envFile):
global env_obj
env_obj = Environment(envFile)
return env_obj
parser = argparse.ArgumentParser(description="testing")
parser.add_argument("--env")
parser.add_argument("--log")
args = parser.parse_args()
env_obj = load_env(args.env)
db_agent(env_obj)
db_agent_download(env_obj)
client_agent(env_obj)
init_scheduler()
app = rest_api(env_obj)
app.run(port=env_obj.rest_api_port, host="0.0.0.0")
class MyServiceFramework(win32serviceutil.ServiceFramework):
_svc_name_ = 'DeviceAgent'
_svc_display_name_ = 'Device Agent Service'
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
self.service_impl.stop()
self.ReportServiceStatus(win32service.SERVICE_STOPPED)
def SvcDoRun(self):
self.service_impl = MyService()
self.ReportServiceStatus(win32service.SERVICE_START_PENDING)
self.ReportServiceStatus(win32service.SERVICE_RUNNING)
self.service_impl.run()
def Main():
if len(sys.argv) == 1:
print("this is if")
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(MyServiceFramework)
servicemanager.StartServiceCtrlDispatcher()
else:
print("this is else",sys.argv)
win32serviceutil.HandleCommandLine(MyServiceFramework)
if __name__ == '__main__':
Main()
What should i do ? how can i run the shellscript along with env.
I want to know how i should pass the argument for env
Related
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.
My Flask service stops because I logged out in Windows. When I reload my username and password, it works again. How can I make it always on, even when I reboot or log out?
import time
import random
import os
from pathlib import Path
from SMWinservice import SMWinservice
import sys
import win32serviceutil
import win32service
import win32event
import servicemanager
class FlaskService(SMWinservice):
_svc_name_ = "FlaskServiceSmartFactory01"
_svc_display_name_ = "Flask Service Smart Factory01"
_svc_description_ = "Python service framework Smart Factory01"
def start(self):
self.isrunning = True
def stop(self):
self.isrunning = False
def main(self):
os.chdir(os.environ['SMARTFACTORYPATH'])
os.system('C02_RestAPI.py')
if __name__ == '__main__':
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(FlaskService)
servicemanager.StartServiceCtrlDispatcher()
else:
win32serviceutil.HandleCommandLine(FlaskService)
Windows services can run in background when Windows is running but you can't run it if Windows is off.
You can set this service to be load at Windows start if you want.
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")