Python script as service on windows

Hello people, if you need to run a script as service on Windows.

You need:

Pyinstaller.

pywin32

python 2.x

And this script called servicedeploy.py:

autor: https://gist.github.com/drmalex07/10554232

import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import time
import logging
import subprocess 
pathexe = r"C:/dist/serviceweb.exe"
logging.basicConfig(
    filename = 'c:\\Temp\\hello-service.log',
    level = logging.DEBUG, 
    format = '[helloworld-service] %(levelname)-7.7s %(message)s'
)
class HelloWorldSvc (win32serviceutil.ServiceFramework):
    _svc_name_ = "SERVICE WEB"
    _svc_display_name_ = "NAME SERVICE"
    def __init__(self,args):
        win32serviceutil.ServiceFramework.__init__(self,args)
        self.stop_event = win32event.CreateEvent(None,0,0,None)
        socket.setdefaulttimeout(60)
        self.stop_requested = False
    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.stop_event)
        logging.info('Stopping 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):
        logging.info(' ** Hello PyWin32 World ** ')
        # Simulate a main loop
        for i in range(0,1):
            if self.stop_requested:
                logging.info('A stop signal was received: Breaking main loop ...')
                break
            time.sleep(5)
            subprocess.Popen([pathexe])  
            logging.info("Hello at %s" % time.ctime())
        return
if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(HelloWorldSvc)

Pyinstaller:

https://www.pyinstaller.org/ PyInstaller is a program that freezes (packages) Python programs into stand-alone executables, under Windows, Linux, Mac OS X, FreeBSD, Solaris and AIX.

Pywin32:

https://github.com/mhammond/pywin32

Win32 (pywin32) extensions, which provides access to many of the Windows APIs from Python.

Getting started

I do this script called serviceweb.py in flask to convert into service:

from flask import Flask 
app = Flask(__name__)
@app.route("/")
def index():
    return "hello world from service"
if __name__ == "__main__":
    app.run(debug=false,host="0.0.0.0", port=900)

Now I need to compile this script (excecutable.exe)

how I do this? I can do it with pyinstaller: Open the CMD and go to the directory where are your script and used this commands:

--onefile: the script compile on one file.

--windowed: the script doesn't run windowed ( the services of windows run without graphic resource)

pyinstaller --onefile --windowed yourscript.py

Example:

My script is on "c:\"

When the pyinstaller finishes correctly, it generates a directory called dist where are your executable with script name.

Now you have a service! and you can executed manuallity.

The next step

Deploy service with pywin32 using servicedeploy.py firt:

1.Edit servicedeployd with favorite editor.

2.Change pathexe with the path of your service.

3.Save the changes

And then, install the service.

Again open your CMD and go to the directory where are servicedeploy.py and do the follow:

python servicedeploy.py install

Result:

you have to start the manual service the first time, you could change it to automatic from the service manager.

Is running:

I am sorry for my bad english. I hope you understand me.

AUTHOR

Hi, Luis Miguel-san. Thank you for writing your first article. I am looking forward to sharing your knowledge.

8 months ago

Hi Luis, Thanks for the write up. However, I could not get your steps to work. Some of the other available documentation suggests that what you are doing is not possible - https://stackoverflow.com/questions/5307968/how-can-i-run-an-exe-program-from-a-windows-service-using-c Cheers

8 months ago

additional reading - https://blogs.msdn.microsoft.com/winsdk/2009/07/14/launching-an-interactive-process-from-windows-service-in-windows-vista-and-later/

READ NEXT

Boostlog is an online community for developers
who want to share ideas and grow each other.

Bitcoin Gambling

Delete an article

Deleted articles are gone forever. Are you sure?