<p>I am sketching the architecture for a set of programs that share various interrelated objects stored in a database. I want one of the programs to act as a service which provides a higher level interface for operations on these objects, and the other programs to access the objects through that service.</p>

<p>I am currently aiming for Python and the Django framework as the technologies to implement that service with. I'm pretty sure I figure how to daemonize the Python program in Linux. However, it is an optional spec item that the system should support Windows. I have little experience with Windows programming and no experience at all with Windows services.</p>

<p><strong>Is it possible to run a Python programs as a Windows service (i. e. run it automatically without user login)?</strong> I won't necessarily have to implement this part, but I need a rough idea how it would be done in order to decide whether to design along these lines.</p>

<p><i>Edit: Thanks for all the answers so far, they are quite comprehensive. I would like to know one more thing: <b>How is Windows aware of my service? Can I manage it with the native Windows utilities?</b> <strong>What is the equivalent of putting a start/stop script in /etc/init.d?</i></strong></p>

[{'answer_id': 32440, 'author': 'Ricardo Reyes', 'author_id': 3399, 'author_profile': 'https://Stackoverflow.com/users/3399', 'pm_score': 9, 'selected': True, 'text': '<p>Yes you can. I do it using the pythoncom libraries that come included with <a href="http://www.activestate.com/Products/activepython/index.mhtml" rel="noreferrer">ActivePython</a> or can be installed with <a href="https://sourceforge.net/projects/pywin32/" rel="noreferrer">pywin32</a> (Python for Windows extensions).</p>\n\n<p>This is a basic skeleton for a simple service:</p>\n\n<pre><code>import win32serviceutil\nimport win32service\nimport win32event\nimport servicemanager\nimport socket\n\n\nclass AppServerSvc (win32serviceutil.ServiceFramework):\n    _svc_name_ = "TestService"\n    _svc_display_name_ = "Test Service"\n\n    def __init__(self,args):\n        win32serviceutil.ServiceFramework.__init__(self,args)\n        self.hWaitStop = win32event.CreateEvent(None,0,0,None)\n        socket.setdefaulttimeout(60)\n\n    def SvcStop(self):\n        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)\n        win32event.SetEvent(self.hWaitStop)\n\n    def SvcDoRun(self):\n        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,\n                              servicemanager.PYS_SERVICE_STARTED,\n                              (self._svc_name_,\'\'))\n        self.main()\n\n    def main(self):\n        pass\n\nif __name__ == \'__main__\':\n    win32serviceutil.HandleCommandLine(AppServerSvc)\n</code></pre>\n\n<p>Your code would go in the <code>main()</code> method—usually with some kind of infinite loop that might be interrupted by checking a flag, which you set in the <code>SvcStop</code> method</p>\n'}, {'answer_id': 597750, 'author': 'popcnt', 'author_id': 47850, 'author_profile': 'https://Stackoverflow.com/users/47850', 'pm_score': 5, 'selected': False, 'text': '<p>There are a couple alternatives for installing as a service virtually any Windows executable.</p>\n\n<h2>Method 1: Use instsrv and srvany from rktools.exe</h2>\n\n<p>For Windows Home Server or Windows Server 2003 (works with WinXP too), the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=9D467A69-57FF-4AE7-96EE-B18C4790CFFD&amp;displaylang=en" rel="nofollow noreferrer">Windows Server 2003 Resource Kit Tools</a> comes with utilities that can be used in tandem for this, called <strong>instsrv.exe</strong> and <strong>srvany.exe</strong>.  See this Microsoft KB article <a href="http://support.microsoft.com/kb/137890" rel="nofollow noreferrer">KB137890</a> for details on how to use these utils.  </p>\n\n<p>For Windows Home Server, there is a great user friendly wrapper for these utilities named aptly "<a href="http://forum.wegotserved.com/index.php?autocom=downloads&amp;showfile=7" rel="nofollow noreferrer">Any Service Installer</a>".  </p>\n\n<h2>Method 2: Use ServiceInstaller for Windows NT</h2>\n\n<p>There is another alternative using <a href="http://www.kcmultimedia.com/smaster/" rel="nofollow noreferrer">ServiceInstaller for Windows NT</a> (<a href="http://www.kcmultimedia.com/smaster/download.html" rel="nofollow noreferrer">download-able here</a>) with <a href="http://conort.googlepages.com/runanywindowsapplicationasntservice" rel="nofollow noreferrer">python instructions available</a>.  Contrary to the name, it works with both Windows 2000 and Windows XP as well.  Here are some instructions for how to install a python script as a service.</p>\n\n<blockquote>\n  <p><strong>Installing a Python script</strong></p>\n  \n  <p>Run ServiceInstaller to create a new\n  service. (In this example, it is\n  assumed that python is installed at\n  c:\\python25)</p>\n\n<pre><code>Service Name  : PythonTest\nDisplay Name : PythonTest \nStartup : Manual (or whatever you like)\nDependencies : (Leave blank or fill to fit your needs)\nExecutable : c:\\python25\\python.exe\nArguments : c:\\path_to_your_python_script\\test.py\nWorking Directory : c:\\path_to_your_python_script\n</code></pre>\n  \n  <p>After installing, open the Control\n  Panel\'s Services applet, select and\n  start the PythonTest service.</p>\n</blockquote>\n\n<p>After my initial answer, I noticed there were closely related Q&amp;A already posted on SO. See also:</p>\n\n<p><a href="https://stackoverflow.com/questions/32404/can-i-run-a-python-script-as-a-service-in-windows-how">Can I run a Python script as a service (in Windows)? How?</a></p>\n\n<p><a href="https://stackoverflow.com/questions/34328/how-do-i-make-windows-aware-of-a-service-i-have-written-in-python">How do I make Windows aware of a service I have written in Python?</a></p>\n'}, {'answer_id': 24996607, 'author': 'mknaf', 'author_id': 1085954, 'author_profile': 'https://Stackoverflow.com/users/1085954', 'pm_score': 6, 'selected': False, 'text': '<p>Although I upvoted the chosen answer a couple of weeks back, in the meantime I struggled a lot more with this topic. It feels like having a special Python installation and using special modules to run a script as a service is simply the wrong way. What about portability and such?</p>\n\n<p>I stumbled across the wonderful <a href="http://nssm.cc/">Non-sucking Service Manager</a>, which made it really simple and sane to deal with Windows Services. I figured since I could pass options to an installed service, I could just as well select my Python executable and pass my script as an option.</p>\n\n<p>I have not yet tried this solution, but I will do so right now and update this post along the process. I am also interested in using virtualenvs on Windows, so I might come up with a tutorial sooner or later and link to it here.</p>\n'}, {'answer_id': 41017425, 'author': 'pyOwner', 'author_id': 5165357, 'author_profile': 'https://Stackoverflow.com/users/5165357', 'pm_score': 5, 'selected': False, 'text': '<p>The simplest way to achieve this is to use native command sc.exe:</p>\n\n<pre><code>sc create PythonApp binPath= "C:\\Python34\\Python.exe --C:\\tmp\\pythonscript.py"\n</code></pre>\n\n<p><strong>References:</strong></p>\n\n<ol>\n<li><a href="https://technet.microsoft.com/en-us/library/cc990289(v=ws.11).aspx" rel="noreferrer">https://technet.microsoft.com/en-us/library/cc990289(v=ws.11).aspx</a></li>\n<li><a href="https://stackoverflow.com/questions/3663331/creating-a-service-with-sc-exe-how-to-pass-in-context-parameters">When creating a service with sc.exe how to pass in context parameters?</a></li>\n</ol>\n'}, {'answer_id': 42587921, 'author': 'Seliverstov Maksim', 'author_id': 7589877, 'author_profile': 'https://Stackoverflow.com/users/7589877', 'pm_score': 3, 'selected': False, 'text': '<p>pysc: <a href="https://pypi.python.org/pypi/pysc" rel="noreferrer">Service Control Manager on Python</a></p>\n\n<p>Example script to run as a service <a href="http://pythonhosted.org/pysc/example.html" rel="noreferrer">taken from pythonhosted.org</a>:</p>\n\n<blockquote>\n<pre><code>from xmlrpc.server import SimpleXMLRPCServer\n\nfrom pysc import event_stop\n\n\nclass TestServer:\n\n    def echo(self, msg):\n        return msg\n\n\nif __name__ == \'__main__\':\n    server = SimpleXMLRPCServer((\'127.0.0.1\', 9001))\n\n    @event_stop\n    def stop():\n        server.server_close()\n\n    server.register_instance(TestServer())\n    server.serve_forever()\n</code></pre>\n  \n  <p><strong>Create and start service</strong></p>\n\n<pre><code>import os\nimport sys\nfrom xmlrpc.client import ServerProxy\n\nimport pysc\n\n\nif __name__ == \'__main__\':\n    service_name = \'test_xmlrpc_server\'\n    script_path = os.path.join(\n        os.path.dirname(__file__), \'xmlrpc_server.py\'\n    )\n    pysc.create(\n        service_name=service_name,\n        cmd=[sys.executable, script_path]\n    )\n    pysc.start(service_name)\n\n    client = ServerProxy(\'http://127.0.0.1:9001\')\n    print(client.echo(\'test scm\'))\n</code></pre>\n  \n  <p><strong>Stop and delete service</strong></p>\n\n<pre><code>import pysc\n\nservice_name = \'test_xmlrpc_server\'\n\npysc.stop(service_name)\npysc.delete(service_name)\n</code></pre>\n</blockquote>\n\n\n\n<pre><code>pip install pysc\n</code></pre>\n'}, {'answer_id': 44820139, 'author': 'Seckin Sanli', 'author_id': 8230298, 'author_profile': 'https://Stackoverflow.com/users/8230298', 'pm_score': 5, 'selected': False, 'text': '<p>Step by step explanation how to make it work :</p>\n\n<p>1- First create a python file according to the basic skeleton mentioned above. And save it to a path for example :  "c:\\PythonFiles\\AppServerSvc.py"</p>\n\n<pre><code>import win32serviceutil\nimport win32service\nimport win32event\nimport servicemanager\nimport socket\n\n\nclass AppServerSvc (win32serviceutil.ServiceFramework):\n    _svc_name_ = "TestService"\n    _svc_display_name_ = "Test Service"\n\n\n    def __init__(self,args):\n        win32serviceutil.ServiceFramework.__init__(self,args)\n        self.hWaitStop = win32event.CreateEvent(None,0,0,None)\n        socket.setdefaulttimeout(60)\n\n    def SvcStop(self):\n        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)\n        win32event.SetEvent(self.hWaitStop)\n\n    def SvcDoRun(self):\n        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,\n                          servicemanager.PYS_SERVICE_STARTED,\n                          (self._svc_name_,\'\'))\n        self.main()\n\n    def main(self):\n        # Your business logic or call to any class should be here\n        # this time it creates a text.txt and writes Test Service in a daily manner \n        f = open(\'C:\\\\test.txt\', \'a\')\n        rc = None\n        while rc != win32event.WAIT_OBJECT_0:\n            f.write(\'Test Service  \\n\')\n            f.flush()\n            # block for 24*60*60 seconds and wait for a stop event\n            # it is used for a one-day loop\n            rc = win32event.WaitForSingleObject(self.hWaitStop, 24 * 60 * 60 * 1000)\n        f.write(\'shut down \\n\')\n        f.close()\n\nif __name__ == \'__main__\':\n    win32serviceutil.HandleCommandLine(AppServerSvc)\n</code></pre>\n\n<p>2 - On this step we should register our service. </p>\n\n<p>Run command prompt as <strong>administrator</strong> and type as: </p>\n\n<blockquote>\n  <p>sc create TestService binpath= "C:\\Python36\\Python.exe c:\\PythonFiles\\AppServerSvc.py" DisplayName= "TestService" start= auto</p>\n</blockquote>\n\n<p>the first argument of <strong>binpath</strong> is the <strong>path of python.exe</strong> </p>\n\n<p>second argument of <strong>binpath</strong>  is <strong>the path of your python file</strong> that we created already</p>\n\n<p>Don\'t miss that you should put one space after every "<strong>=</strong>" sign. </p>\n\n<p>Then if everything is ok, you should see </p>\n\n<blockquote>\n  <p>[SC] CreateService SUCCESS</p>\n</blockquote>\n\n<p>Now your python service is installed as windows service now. You can see it in Service Manager and registry  under : </p>\n\n<p>HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\TestService</p>\n\n<p>3- Ok now. You can start your service on service manager. </p>\n\n<p>You can execute every python file that provides this service skeleton.  </p>\n'}, {'answer_id': 46450007, 'author': 'Adriano  P', 'author_id': 8221383, 'author_profile': 'https://Stackoverflow.com/users/8221383', 'pm_score': 6, 'selected': False, 'text': "<p>The simplest way is to use the: <strong>NSSM - the Non-Sucking Service Manager.</strong> Just download and unzip to a location of your choosing. It's a self-contained utility, around 300KB (much less than installing the entire pywin32 suite just for this purpose) and no &quot;installation&quot; is needed. The zip contains a 64-bit and a 32-bit version of the utility. Either should work well on current systems (you can use the 32-bit version to manage services on 64-bit systems).</p>\n<h3>GUI approach</h3>\n<p><strong>1 - install the python program as a service. Open a Win prompt as admin</strong></p>\n<pre><code>c:\\&gt;nssm.exe install WinService\n</code></pre>\n<p><strong>2 - On NSSM´s GUI console:</strong></p>\n<p>path: C:\\Python27\\Python27.exe</p>\n<p>Startup directory: C:\\Python27</p>\n<p>Arguments: c:\\WinService.py</p>\n<p><strong>3 - check the created services on services.msc</strong></p>\n<h3>Scripting approach (no GUI)</h3>\n<p>This is handy if your service should be part of an automated, non-interactive procedure, that may be beyond your control, such as a batch or installer script. It is assumed that the commands are executed with administrative privileges.</p>\n<p>For convenience the commands are described here by simply referring to the utility as <code>nssm.exe</code>. It is advisable, however, to refer to it more explicitly in scripting with its full path <code>c:\\path\\to\\nssm.exe</code>, since it's a self-contained executable that may be located in a private path that the system is not aware of.</p>\n<p><strong>1. Install the service</strong></p>\n<p>You must specify a name for the service, the path to the proper Python executable, and the path to the script:</p>\n<pre><code>nssm.exe install ProjectService &quot;c:\\path\\to\\python.exe&quot; &quot;c:\\path\\to\\project\\app\\main.py&quot;\n</code></pre>\n<p>More explicitly:</p>\n<pre><code>nssm.exe install ProjectService \nnssm.exe set ProjectService Application &quot;c:\\path\\to\\python.exe&quot;\nnssm.exe set ProjectService AppParameters &quot;c:\\path\\to\\project\\app\\main.py&quot;\n</code></pre>\n<p>Alternatively you may want your Python app to be started as a Python module. One easy approach is to tell nssm that it needs to change to the proper starting directory, as you would do yourself when launching from a command shell:</p>\n<pre><code>nssm.exe install ProjectService &quot;c:\\path\\to\\python.exe&quot; &quot;-m app.main&quot;\nnssm.exe set ProjectService AppDirectory &quot;c:\\path\\to\\project&quot;\n</code></pre>\n<p>This approach works well with virtual environments and self-contained (embedded) Python installs. Just make sure to have properly resolved any path issues in those environments with the usual methods. nssm has a way to set environment variables (e.g. PYTHONPATH) if needed, and can also launch batch scripts.</p>\n<p><strong>2. To start the service</strong></p>\n<pre><code>nssm.exe start ProjectService \n</code></pre>\n<p><strong>3. To stop the service</strong></p>\n<pre><code>nssm.exe stop ProjectService\n</code></pre>\n<p><strong>4. To remove the service</strong>, specify the <code>confirm</code> parameter to skip the interactive confirmation.</p>\n<pre><code>nssm.exe remove ProjectService confirm\n</code></pre>\n"}, {'answer_id': 52780201, 'author': 'flam3', 'author_id': 1407255, 'author_profile': 'https://Stackoverflow.com/users/1407255', 'pm_score': 2, 'selected': False, 'text': '<p>I started hosting as a service with <a href="https://stackoverflow.com/a/32440/1407255">pywin32</a>.</p>\n\n<p>Everything was well but I met the problem that service was not able to start within 30 seconds (default timeout for Windows) on system startup. It was critical for me because Windows startup took place simultaneous on several virtual machines hosted on one physical machine, and IO load was huge.\nError messages were:</p>\n\n<p><code>Error 1053: The service did not respond to the start or control request in a timely fashion.</code></p>\n\n<p><code>Error 7009: Timeout (30000 milliseconds) waiting for the &lt;ServiceName&gt; service to connect.</code></p>\n\n<p>I fought a lot with pywin, but ended up with using NSSM as it was proposed <a href="https://stackoverflow.com/a/24996607/1407255">in this answer</a>. It was very easy to migrate to it.</p>\n'}, {'answer_id': 53240642, 'author': 'ndemou', 'author_id': 1011025, 'author_profile': 'https://Stackoverflow.com/users/1011025', 'pm_score': 1, 'selected': False, 'text': '<p>The accepted answer using <code>win32serviceutil</code> works but is complicated and makes debugging and changes harder. It is <strong><em>far</em></strong> easier to use NSSM (<a href="https://nssm.cc" rel="nofollow noreferrer">the Non-Sucking Service Manager)</a>. You write and comfortably debug a normal python program and when it finally works you use NSSM to install it as a service in less than a minute:</p>\n\n<p>From an elevated (admin) command prompt you run <code>nssm.exe install NameOfYourService</code> and you fill-in these options:</p>\n\n<ul>\n<li><strong>path</strong>: (the path to python.exe e.g. <code>C:\\Python27\\Python.exe</code>)</li>\n<li><strong>Arguments</strong>: (the path to your python script, e.g. <code>c:\\path\\to\\program.py</code>)</li>\n</ul>\n\n<p>By the way, if your program prints useful messages that you want to keep in a log file NSSM can also handle this and a lot more for you.</p>\n'}, {'answer_id': 56451724, 'author': 'coder', 'author_id': 10534497, 'author_profile': 'https://Stackoverflow.com/users/10534497', 'pm_score': 3, 'selected': False, 'text': '<p><strong><a href="https://nssm.cc/download" rel="nofollow noreferrer">nssm</a> in python 3+</strong></p>\n\n<p>(I converted my .py file to .exe with <a href="https://www.pyinstaller.org/downloads.html" rel="nofollow noreferrer">pyinstaller</a>)</p>\n\n<p>nssm:\nas said before</p>\n\n<ul>\n<li>run nssm install {ServiceName}</li>\n<li><p><strong>On NSSM´s console:</strong></p>\n\n<p><strong>path: <em>path\\to\\your\\program.exe</em></strong></p>\n\n<p><strong>Startup directory: <em>path\\to\\your\\ #same as the path but without your program.exe</em></strong></p>\n\n<p><strong>Arguments: empty</strong></p></li>\n</ul>\n\n<p><strong>If you don\'t want to convert your project to .exe</strong> </p>\n\n<ul>\n<li>create a .bat file with <code>python {{your python.py file name}}</code></li>\n<li>and set the path to the .bat file</li>\n</ul>\n'}, {'answer_id': 59923084, 'author': 'Alias_Knagg', 'author_id': 2156089, 'author_profile': 'https://Stackoverflow.com/users/2156089', 'pm_score': 2, 'selected': False, 'text': '<h1>A complete pywin32 example using loop or subthread</h1>\n<p>After working on this on and off for a few days, here is the answer I would have wished to find, using pywin32 to keep it nice and self contained.</p>\n<p>This is complete working code for one loop-based and one thread-based solution.\nIt may work on both python 2 and 3, although I\'ve only tested the latest version on 2.7 and Win7. The loop should be good for polling code, and the tread should work with more server-like code. It seems to work nicely with the <a href="https://docs.pylonsproject.org/projects/waitress/en/latest/" rel="nofollow noreferrer">waitress</a> wsgi server that does not have a standard way to shut down gracefully.</p>\n<p>I would also like to note that there seems to be loads of examples out there, like <a href="https://www.thepythoncorner.com/2018/08/how-to-create-a-windows-service-in-python/" rel="nofollow noreferrer">this</a> that are almost useful, but in reality misleading, because they have cut and pasted other examples blindly. I could be wrong. but why create an event if you never wait for it?</p>\n<p>That said I still feel I\'m on somewhat shaky ground here, especially with regards to how clean the exit from the thread version is, but at least I believe there are nothing <em>misleading</em> here.</p>\n<p>To run simply copy the code to a file and follow the instructions.</p>\n<h3>update:</h3>\n<p>Use a simple flag to terminate thread. The important bit is that &quot;thread done&quot; prints.<br />\nFor a more elaborate example exiting from an uncooperative server thread see my <a href="https://stackoverflow.com/questions/59893782/how-to-exit-cleanly-from-flask-and-waitress-running-as-a-windows-pywin32-service">post about the waitress wsgi server</a>.</p>\n<pre><code># uncomment mainthread() or mainloop() call below\n# run without parameters to see HandleCommandLine options\n# install service with &quot;install&quot; and remove with &quot;remove&quot;\n# run with &quot;debug&quot; to see print statements\n# with &quot;start&quot; and &quot;stop&quot; watch for files to appear\n# check Windows EventViever for log messages\n\nimport socket\nimport sys\nimport threading\nimport time\nfrom random import randint\nfrom os import path\n\nimport servicemanager\nimport win32event\nimport win32service\nimport win32serviceutil\n# see http://timgolden.me.uk/pywin32-docs/contents.html for details\n\n\ndef dummytask_once(msg=\'once\'):\n    fn = path.join(path.dirname(__file__),\n                \'%s_%s.txt\' % (msg, randint(1, 10000)))\n    with open(fn, \'w\') as fh:\n        print(fn)\n        fh.write(\'\')\n\n\ndef dummytask_loop():\n    global do_run\n    while do_run:\n        dummytask_once(msg=\'loop\')\n        time.sleep(3)\n\n\nclass MyThread(threading.Thread):\n    def __init__(self):\n        threading.Thread.__init__(self)\n\n    def run(self):\n        global do_run\n        do_run = True\n        print(\'thread start\\n\')\n        dummytask_loop()\n        print(\'thread done\\n\')\n\n    def exit(self):\n        global do_run\n        do_run = False\n\n\nclass SMWinservice(win32serviceutil.ServiceFramework):\n    _svc_name_ = \'PyWinSvc\'\n    _svc_display_name_ = \'Python Windows Service\'\n    _svc_description_ = \'An example of a windows service in Python\'\n\n    @classmethod\n    def parse_command_line(cls):\n        win32serviceutil.HandleCommandLine(cls)\n\n    def __init__(self, args):\n        win32serviceutil.ServiceFramework.__init__(self, args)\n        self.stopEvt = win32event.CreateEvent(None, 0, 0, None)  # create generic event\n        socket.setdefaulttimeout(60)\n\n    def SvcStop(self):\n        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,\n                            servicemanager.PYS_SERVICE_STOPPED,\n                            (self._svc_name_, \'\'))\n        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)\n        win32event.SetEvent(self.stopEvt)  # raise event\n\n    def SvcDoRun(self):\n        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,\n                            servicemanager.PYS_SERVICE_STARTED,\n                            (self._svc_name_, \'\'))\n        # UNCOMMENT ONE OF THESE\n        # self.mainthread()\n        # self.mainloop()\n\n    # Wait for stopEvt indefinitely after starting thread.\n    def mainthread(self):\n        print(\'main start\')\n        self.server = MyThread()\n        self.server.start()\n        print(\'wait for win32event\')\n        win32event.WaitForSingleObject(self.stopEvt, win32event.INFINITE)\n        self.server.exit()\n        print(\'wait for thread\')\n        self.server.join()\n        print(\'main done\')\n\n    # Wait for stopEvt event in loop.\n    def mainloop(self):\n        print(\'loop start\')\n        rc = None\n        while rc != win32event.WAIT_OBJECT_0:\n            dummytask_once()\n            rc = win32event.WaitForSingleObject(self.stopEvt, 3000)\n        print(\'loop done\')\n\n\nif __name__ == \'__main__\':\n    SMWinservice.parse_command_line()\n</code></pre>\n'}, {'answer_id': 60775892, 'author': 'gunarajulu renganathan', 'author_id': 13095056, 'author_profile': 'https://Stackoverflow.com/users/13095056', 'pm_score': -1, 'selected': False, 'text': '<p><a href="https://www.chrisumbel.com/article/windows_services_in_python" rel="nofollow noreferrer">https://www.chrisumbel.com/article/windows_services_in_python</a></p>\n\n<ol>\n<li><p>Follow up the PySvc.py</p></li>\n<li><p>changing the dll folder </p></li>\n</ol>\n\n<p>I know this is old but I was stuck on this forever. For me, this specific problem was solved by copying this file - pywintypes36.dll</p>\n\n<p>From -> Python36\\Lib\\site-packages\\pywin32_system32</p>\n\n<p>To -> Python36\\Lib\\site-packages\\win32</p>\n\n<pre><code>setx /M PATH "%PATH%;C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python38-32;C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python38-32\\Scripts;C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python38-32\\Lib\\site-packages\\pywin32_system32;C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python38-32\\Lib\\site-packages\\win32\n</code></pre>\n\n<ol start="3">\n<li>changing the path to python folder by</li>\n</ol>\n\n<p><code>cd C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python38-32</code></p>\n\n<ol start="4">\n<li><code>NET START PySvc</code></li>\n<li><code>NET STOP PySvc</code></li>\n</ol>\n'}, {'answer_id': 64637599, 'author': 'Russell McDonell', 'author_id': 12791160, 'author_profile': 'https://Stackoverflow.com/users/12791160', 'pm_score': 2, 'selected': False, 'text': "<p>This answer is plagiarizer from several sources on StackOverflow - most of them above, but I've forgotten the others - sorry. It's simple and scripts run &quot;as is&quot;. For releases you test you script, then copy it to the server and Stop/Start the associated service. And it should work for all scripting languages (Python, Perl, node.js), plus batch scripts such as GitBash, PowerShell, even old DOS bat scripts.\npyGlue is the glue that sits between Windows Services and your script.</p>\n<pre><code>'''\nA script to create a Windows Service, which, when started, will run an executable with the specified parameters.\nOptionally, you can also specify a startup directory\n\nTo use this script you MUST define (in class Service)\n1. A name for your service (short - preferably no spaces)\n2. A display name for your service (the name visibile in Windows Services)\n3. A description for your service (long details visible when you inspect the service in Windows Services)\n4. The full path of the executable (usually C:/Python38/python.exe or C:WINDOWS/System32/WindowsPowerShell/v1.0/powershell.exe\n5. The script which Python or PowerShell will run(or specify None if your executable is standalone - in which case you don't need pyGlue)\n6. The startup directory (or specify None)\n7. Any parameters for your script (or for your executable if you have no script)\n\nNOTE: This does not make a portable script.\nThe associated '_svc_name.exe' in the dist folder will only work if the executable,\n(and any optional startup directory) actually exist in those locations on the target system\n\nUsage: 'pyGlue.exe [options] install|update|remove|start [...]|stop|restart [...]|debug [...]'\nOptions for 'install' and 'update' commands only:\n        --username domain\\\\username : The Username the service is to run under\n        --password password : The password for the username\n        --startup [manual|auto|disabled|delayed] : How the service starts, default = manual\n        --interactive : Allow the service to interact with the desktop.\n        --perfmonini file: .ini file to use for registering performance monitor data\n        --perfmondll file: .dll file to use when querying the service for performance data, default = perfmondata.dll\nOptions for 'start' and 'stop' commands only:\n        --wait seconds: Wait for the service to actually start or stop.\n                If you specify --wait with the 'stop' option, the service and all dependent services will be stopped,\n                each waiting the specified period.\n'''\n\n# Import all the modules that make life easy\nimport servicemanager\nimport socket\nimport sys\nimport win32event\nimport win32service\nimport win32serviceutil\nimport win32evtlogutil\nimport os\nfrom logging import Formatter, Handler\nimport logging\nimport subprocess\n\n\n# Define the win32api class\nclass Service (win32serviceutil.ServiceFramework):\n        # The following variable are edited by the build.sh script\n        _svc_name_ = &quot;TestService&quot;\n        _svc_display_name_ = &quot;Test Service&quot;\n        _svc_description_ = &quot;Test Running Python Scripts as a Service&quot;\n        service_exe = 'c:/Python27/python.exe'\n        service_script = None\n        service_params = []\n        service_startDir = None\n\n        # Initialize the service\n        def __init__(self, args):\n                win32serviceutil.ServiceFramework.__init__(self, args)\n                self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)\n                self.configure_logging()\n                socket.setdefaulttimeout(60)\n\n        # Configure logging to the WINDOWS Event logs\n        def configure_logging(self):\n                self.formatter = Formatter('%(message)s')\n                self.handler = logHandler()\n                self.handler.setFormatter(self.formatter)\n                self.logger = logging.getLogger()\n                self.logger.addHandler(self.handler)\n                self.logger.setLevel(logging.INFO)\n\n        # Stop the service\n        def SvcStop(self):\n                self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)\n                win32event.SetEvent(self.hWaitStop)\n\n        # Run the service\n        def SvcDoRun(self):\n                self.main()\n\n        # This is the service\n        def main(self):\n\n                # Log that we are starting\n                servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED,\n                                                          (self._svc_name_, ''))\n\n                # Fire off the real process that does the real work\n                logging.info('%s - about to call Popen() to run %s %s %s', self._svc_name_, self.service_exe, self.service_script, self.service_params)\n                self.process = subprocess.Popen([self.service_exe, self.service_script] + self.service_params, shell=False, cwd=self.service_startDir)\n                logging.info('%s - started process %d', self._svc_name_, self.process.pid)\n\n                # Wait until WINDOWS kills us - retrigger the wait for stop every 60 seconds\n                rc = None\n                while rc != win32event.WAIT_OBJECT_0:\n                        rc = win32event.WaitForSingleObject(self.hWaitStop, (1 * 60 * 1000))\n\n                # Shut down the real process and exit\n                logging.info('%s - is terminating process %d', self._svc_name_, self.process.pid)\n                self.process.terminate()\n                logging.info('%s - is exiting', self._svc_name_)\n\n\nclass logHandler(Handler):\n        '''\nEmit a log record to the WINDOWS Event log\n        '''\n\n        def emit(self, record):\n                servicemanager.LogInfoMsg(record.getMessage())\n\n\n# The main code\nif __name__ == '__main__':\n        '''\nCreate a Windows Service, which, when started, will run an executable with the specified parameters.\n        '''\n\n        # Check that configuration contains valid values just in case this service has accidentally\n        # been moved to a server where things are in different places\n        if not os.path.isfile(Service.service_exe):\n                print('Executable file({!s}) does not exist'.format(Service.service_exe), file=sys.stderr)\n                sys.exit(0)\n        if not os.access(Service.service_exe, os.X_OK):\n                print('Executable file({!s}) is not executable'.format(Service.service_exe), file=sys.stderr)\n                sys.exit(0)\n        # Check that any optional startup directory exists\n        if (Service.service_startDir is not None) and (not os.path.isdir(Service.service_startDir)):\n                print('Start up directory({!s}) does not exist'.format(Service.service_startDir), file=sys.stderr)\n                sys.exit(0)\n\n        if len(sys.argv) == 1:\n                servicemanager.Initialize()\n                servicemanager.PrepareToHostSingle(Service)\n                servicemanager.StartServiceCtrlDispatcher()\n        else:\n                # install/update/remove/start/stop/restart or debug the service\n                # One of those command line options must be specified\n                win32serviceutil.HandleCommandLine(Service)\n</code></pre>\n<p>Now there's a bit of editing and you don't want all your services called 'pyGlue'. So there's a script (build.sh) to plug in the bits and create a customized 'pyGlue' and create an '.exe'. It is this '.exe' which gets installed as a Windows Service. Once installed you can set it to run automatically.</p>\n<pre><code>#!/bin/sh\n# This script build a Windows Service that will install/start/stop/remove a service that runs a script\n# That is, executes Python to run a Python script, or PowerShell to run a PowerShell script, etc\n\nif [ $# -lt 6 ]; then\n        echo &quot;Usage: build.sh Name Display Description Executable Script StartupDir [Params]...&quot;\n        exit 0\nfi\n\nname=$1\ndisplay=$2\ndesc=$3\nexe=$4\nscript=$5\nstartDir=$6\nshift; shift; shift; shift; shift; shift\nparams=\nwhile [ $# -gt 0 ]; do\n        if [ &quot;${params}&quot; != &quot;&quot; ]; then\n                params=&quot;${params}, &quot;\n        fi\n        params=&quot;${params}'$1'&quot;\n        shift\ndone\n\ncat pyGlue.py | sed -e &quot;s/pyGlue/${name}/g&quot; | \\\n        sed -e &quot;/_svc_name_ =/s?=.*?= '${name}'?&quot; | \\\n        sed -e &quot;/_svc_display_name_ =/s?=.*?= '${display}'?&quot; | \\\n        sed -e &quot;/_svc_description_ =/s?=.*?= '${desc}'?&quot; | \\\n        sed -e &quot;/service_exe =/s?=.*?= '$exe'?&quot; | \\\n        sed -e &quot;/service_script =/s?=.*?= '$script'?&quot; | \\\n        sed -e &quot;/service_params =/s?=.*?= [${params}]?&quot; | \\\n        sed -e &quot;/service_startDir =/s?=.*?= '${startDir}'?&quot; &gt; ${name}.py\n\ncxfreeze ${name}.py --include-modules=win32timezone\n</code></pre>\n<p>Installation - copy the '.exe' the server and the script to the specified folder. Run the '.exe', as Administrator, with the 'install' option. Open Windows Services, as Adminstrator, and start you service. For upgrade, just copy the new version of the script and Stop/Start the service.</p>\n<p>Now every server is different - different installations of Python, different folder structures. I maintain a folder for every server, with a copy of pyGlue.py and build.sh. And I create a 'serverBuild.sh' script for rebuilding all the service on that server.</p>\n<pre><code># A script to build all the script based Services on this PC\nsh build.sh AutoCode 'AutoCode Medical Documents' 'Autocode Medical Documents to SNOMED_CT and AIHW codes' C:/Python38/python.exe autocode.py C:/Users/russell/Documents/autocoding -S -T\n</code></pre>\n"}, {'answer_id': 72627675, 'author': 'Matthias Luh', 'author_id': 2738240, 'author_profile': 'https://Stackoverflow.com/users/2738240', 'pm_score': 1, 'selected': False, 'text': '<p>This doesn\'t answer the original question, but might help other people that want to automatically start a Python script at Windows startup:\nHave a look at the <a href="https://en.wikipedia.org/wiki/Windows_Task_Scheduler" rel="nofollow noreferrer">Windows Task Scheduler</a> instead, it is way easier if you just want to start a script after boot without all the service functionality of a Windows Service.</p>\n<p>Create a new task, select &quot;At startup&quot; as trigger, &quot;Start program&quot; as action with &quot;C:\\Python39\\python.exe&quot; as the program (or wherever your python.exe is) and the full path to your script (&quot;C:...\\my_dir\\xyz.py&quot;) as argument (you can use &quot; if the path contains spaces).\nYou can also select the path of your script (without the .py file, e.g. &quot;C:...\\my_dir&quot;) for &quot;start in&quot; if you use relative paths in your script, e.g. for logging.</p>\n'}]
['https://Stackoverflow.com/questions/32404', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2077/']