How do you run a Python script as a service in Windows?
up vote
220
down vote
favorite
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.
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.
Is it possible to run a Python programs as a Windows service (i. e. run it automatically without user login)? 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.
Edit: Thanks for all the answers so far, they are quite comprehensive. I would like to know one more thing: How is Windows aware of my service? Can I manage it with the native Windows utilities? What is the equivalent of putting a start/stop script in /etc/init.d?
python windows cross-platform
add a comment |
up vote
220
down vote
favorite
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.
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.
Is it possible to run a Python programs as a Windows service (i. e. run it automatically without user login)? 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.
Edit: Thanks for all the answers so far, they are quite comprehensive. I would like to know one more thing: How is Windows aware of my service? Can I manage it with the native Windows utilities? What is the equivalent of putting a start/stop script in /etc/init.d?
python windows cross-platform
2
Check this Windows Service template it uses the win32service API.
– CMS
Feb 28 '09 at 5:52
add a comment |
up vote
220
down vote
favorite
up vote
220
down vote
favorite
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.
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.
Is it possible to run a Python programs as a Windows service (i. e. run it automatically without user login)? 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.
Edit: Thanks for all the answers so far, they are quite comprehensive. I would like to know one more thing: How is Windows aware of my service? Can I manage it with the native Windows utilities? What is the equivalent of putting a start/stop script in /etc/init.d?
python windows cross-platform
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.
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.
Is it possible to run a Python programs as a Windows service (i. e. run it automatically without user login)? 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.
Edit: Thanks for all the answers so far, they are quite comprehensive. I would like to know one more thing: How is Windows aware of my service? Can I manage it with the native Windows utilities? What is the equivalent of putting a start/stop script in /etc/init.d?
python windows cross-platform
python windows cross-platform
edited Feb 27 at 21:29
Undo♦
22.8k2086112
22.8k2086112
asked Aug 28 '08 at 14:28
Hanno Fietz
13.3k41124223
13.3k41124223
2
Check this Windows Service template it uses the win32service API.
– CMS
Feb 28 '09 at 5:52
add a comment |
2
Check this Windows Service template it uses the win32service API.
– CMS
Feb 28 '09 at 5:52
2
2
Check this Windows Service template it uses the win32service API.
– CMS
Feb 28 '09 at 5:52
Check this Windows Service template it uses the win32service API.
– CMS
Feb 28 '09 at 5:52
add a comment |
9 Answers
9
active
oldest
votes
up vote
227
down vote
accepted
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
15
After coding this, how do I tell Windows to run this as a service?
– Kit
Sep 19 '10 at 23:44
30
@Kit: run your script with the from the command line with the parameter "install". Then you'll be able to see your application in Windows' Services list, where you can start it, stop it, or set it to start automatically
– Ricardo Reyes
Sep 22 '10 at 12:29
16
You give special mention to pythoncom, and you import it in your example code. The problem is you never actually use pythoncom anywhere in your example code, you only import it. Why give it special mention and then not show its usage?
– Buttons840
Apr 12 '11 at 17:56
9
Why for thesocket.setdefaulttimeout(60)
is? Is it needed for a service, or was it just accidentaly copied from some existing service? :)
– Timur
Sep 10 '11 at 12:42
6
chrisumbel.com/article/windows_services_in_python This one is a similar example but more complete
– csprabala
May 27 '15 at 15:55
|
show 15 more comments
up vote
31
down vote
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?
I stumbled across the wonderful Non-sucking Service Manager, 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.
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.
Any luck? I'm building a very simple site for a client and don't need to use the whole Apache stack. Also building the service by myself has sounded like an invite for trouble too, as I have read from other comments.
– Jaran
Aug 17 '14 at 12:25
Yes, this works and it is very easy to do. You just give the path and arguments for the script. I was able to get mine to run with out a console just in case someone ends up with a console window somehow.
– kmcguire
Sep 9 '14 at 13:44
While this apparently works, there are other difficulties especially when you "don't need to use the whole Apache stack": gunicorn for example doesn't run on Windows yet, which actually was the showstopper for me.
– mknaf
Sep 9 '14 at 19:15
2
The trick here is to run python.exe as a service and your python script as the parameter: like "nssm install MyServiceName c:python27python.exe c:tempmyscript.py"
– poleguy
Nov 23 '15 at 23:22
Works great! On a system with multiple virtual environments, the path can reference the Python interpreter exe in the Scripts directory of the desired virtual environment. It seems likenew-service
in PowerShell should be able to do this, but starting (and monitoring) a script as a service evidently involves a lot more details, which nssm takes care of very nicely.
– Fred Schleifer
Dec 22 '15 at 7:23
add a comment |
up vote
24
down vote
There are a couple alternatives for installing as a service virtually any Windows executable.
Method 1: Use instsrv and srvany from rktools.exe
For Windows Home Server or Windows Server 2003 (works with WinXP too), the Windows Server 2003 Resource Kit Tools comes with utilities that can be used in tandem for this, called instsrv.exe and srvany.exe. See this Microsoft KB article KB137890 for details on how to use these utils.
For Windows Home Server, there is a great user friendly wrapper for these utilities named aptly "Any Service Installer".
Method 2: Use ServiceInstaller for Windows NT
There is another alternative using ServiceInstaller for Windows NT (download-able here) with python instructions available. 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.
Installing a Python script
Run ServiceInstaller to create a new
service. (In this example, it is
assumed that python is installed at
c:python25)
Service Name : PythonTest
Display Name : PythonTest
Startup : Manual (or whatever you like)
Dependencies : (Leave blank or fill to fit your needs)
Executable : c:python25python.exe
Arguments : c:path_to_your_python_scripttest.py
Working Directory : c:path_to_your_python_script
After installing, open the Control
Panel's Services applet, select and
start the PythonTest service.
After my initial answer, I noticed there were closely related Q&A already posted on SO. See also:
Can I run a Python script as a service (in Windows)? How?
How do I make Windows aware of a service I have written in Python?
I just noticed there are other similar Q&A already: stackoverflow.com/questions/32404/… stackoverflow.com/questions/34328/…
– popcnt
Feb 28 '09 at 8:44
Service Installer doesn't working on a 64 bit architecture so option 1 becomes the goto option.
– Noah Campbell
Jun 10 '11 at 20:02
The above link to ServiceInstaller no longer works. I found it here: sites.google.com/site/conort/…
– LarsH
Nov 14 '11 at 17:25
1
off note, I don't thinkNT
would be necessarily "contrary" to the name, at least not in programmer-folk speech. It just refers to the "NT architecture", as opposed to the "NT brand". That said, according to talk on wikipedia this is up to debate, since "it's not an official Microsoft term", but there is nevertheless a tradition with this line of thinking.
– n611x007
Jul 9 '14 at 8:30
add a comment |
up vote
17
down vote
The simplest way to achive this is to use native command sc.exe:
sc create PythonApp binPath= "C:Python34Python.exe --C:tmppythonscript.py"
- https://technet.microsoft.com/en-us/library/cc990289(v=ws.11).aspx
- creating a service with sc.exe; how to pass in context parameters
add a comment |
up vote
12
down vote
The simplest way is to use the: NSSM - the Non-Sucking Service Manager:
1 - make download on https://nssm.cc/download
2 - install the python program as a service: Win prompt as admin
c:>nssm.exe install WinService
3 - On NSSM´s console:
path: C:Python27Python27.exe
Startup directory: C:Python27
Arguments: c:WinService.py
4 - check the created services on services.msc
add a comment |
up vote
9
down vote
Step by step explanation how to make it work :
1- First create a python file according to the basic skeleton mentioned above. And save it to a path for example : "c:PythonFilesAppServerSvc.py"
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):
# Your business logic or call to any class should be here
# this time it creates a text.txt and writes Test Service in a daily manner
f = open('C:\test.txt', 'a')
rc = None
while rc != win32event.WAIT_OBJECT_0:
f.write('Test Service n')
f.flush()
# block for 24*60*60 seconds and wait for a stop event
# it is used for a one-day loop
rc = win32event.WaitForSingleObject(self.hWaitStop, 24 * 60 * 60 * 1000)
f.write('shut down n')
f.close()
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(AppServerSvc)
2 - On this step we should register our service.
Run command prompt as administrator and type as:
sc create TestService binpath= "C:Python36Python.exe c:PythonFilesAppServerSvc.py" DisplayName= "TestService" start= auto
the first argument of binpath is the path of python.exe
second argument of binpath is the path of your python file that we created already
Don't miss that you should put one space after every "=" sign.
Then if everything is ok, you should see
[SC] CreateService SUCCESS
Now your python service is installed as windows service now. You can see it in Service Manager and registry under :
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesTestService
3- Ok now. You can start your service on service manager.
You can execute every python file that provides this service skeleton.
add a comment |
up vote
1
down vote
I started hosting as a service with pywin32.
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.
Error messages were:
Error 1053: The service did not respond to the start or control request in a timely fashion.
Error 7009: Timeout (30000 milliseconds) waiting for the <ServiceName> service to connect.
I fought a lot with pywin, but ended up with using NSSM as it was proposed in this answer. It was very easy to migrate to it.
add a comment |
up vote
0
down vote
The accepted answer using win32serviceutil
works but is complicated and makes debugging and changes harder. It is far easier to use NSSM (the Non-Sucking Service Manager). 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:
From an elevated (admin) command prompt you run nssm.exe install NameOfYourService
and you fill-in these options:
path: (the path to python.exe e.g.C:Python27Python.exe
)
Arguments: (the path to your python script, e.g.c:pathtoprogram.py
)
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.
Yes, this is a duplicate of Adriano's answer. I upvoted that answer and tried to edit it but after the edits I was looking at a new answer.
– ndemou
Nov 10 at 15:59
add a comment |
up vote
-2
down vote
pysc: Service Control Manager on Python
Example script to run as a service taken from pythonhosted.org:
from xmlrpc.server import SimpleXMLRPCServer
from pysc import event_stop
class TestServer:
def echo(self, msg):
return msg
if __name__ == '__main__':
server = SimpleXMLRPCServer(('127.0.0.1', 9001))
@event_stop
def stop():
server.server_close()
server.register_instance(TestServer())
server.serve_forever()
Create and start service
import os
import sys
from xmlrpc.client import ServerProxy
import pysc
if __name__ == '__main__':
service_name = 'test_xmlrpc_server'
script_path = os.path.join(
os.path.dirname(__file__), 'xmlrpc_server.py'
)
pysc.create(
service_name=service_name,
cmd=[sys.executable, script_path]
)
pysc.start(service_name)
client = ServerProxy('http://127.0.0.1:9001')
print(client.echo('test scm'))
Stop and delete service
import pysc
service_name = 'test_xmlrpc_server'
pysc.stop(service_name)
pysc.delete(service_name)
pip install pysc
Does anyone know why this got a downvote? It looks like a nice solution.
– Jarrod Chesney
Jul 15 '17 at 13:22
4
I've tried this approach, it doesn't work.
– Jarrod Chesney
Jul 16 '17 at 2:53
add a comment |
9 Answers
9
active
oldest
votes
9 Answers
9
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
227
down vote
accepted
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
15
After coding this, how do I tell Windows to run this as a service?
– Kit
Sep 19 '10 at 23:44
30
@Kit: run your script with the from the command line with the parameter "install". Then you'll be able to see your application in Windows' Services list, where you can start it, stop it, or set it to start automatically
– Ricardo Reyes
Sep 22 '10 at 12:29
16
You give special mention to pythoncom, and you import it in your example code. The problem is you never actually use pythoncom anywhere in your example code, you only import it. Why give it special mention and then not show its usage?
– Buttons840
Apr 12 '11 at 17:56
9
Why for thesocket.setdefaulttimeout(60)
is? Is it needed for a service, or was it just accidentaly copied from some existing service? :)
– Timur
Sep 10 '11 at 12:42
6
chrisumbel.com/article/windows_services_in_python This one is a similar example but more complete
– csprabala
May 27 '15 at 15:55
|
show 15 more comments
up vote
227
down vote
accepted
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
15
After coding this, how do I tell Windows to run this as a service?
– Kit
Sep 19 '10 at 23:44
30
@Kit: run your script with the from the command line with the parameter "install". Then you'll be able to see your application in Windows' Services list, where you can start it, stop it, or set it to start automatically
– Ricardo Reyes
Sep 22 '10 at 12:29
16
You give special mention to pythoncom, and you import it in your example code. The problem is you never actually use pythoncom anywhere in your example code, you only import it. Why give it special mention and then not show its usage?
– Buttons840
Apr 12 '11 at 17:56
9
Why for thesocket.setdefaulttimeout(60)
is? Is it needed for a service, or was it just accidentaly copied from some existing service? :)
– Timur
Sep 10 '11 at 12:42
6
chrisumbel.com/article/windows_services_in_python This one is a similar example but more complete
– csprabala
May 27 '15 at 15:55
|
show 15 more comments
up vote
227
down vote
accepted
up vote
227
down vote
accepted
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
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
edited Nov 14 '16 at 4:26
artburkart
7861022
7861022
answered Aug 28 '08 at 14:39
Ricardo Reyes
6,39742119
6,39742119
15
After coding this, how do I tell Windows to run this as a service?
– Kit
Sep 19 '10 at 23:44
30
@Kit: run your script with the from the command line with the parameter "install". Then you'll be able to see your application in Windows' Services list, where you can start it, stop it, or set it to start automatically
– Ricardo Reyes
Sep 22 '10 at 12:29
16
You give special mention to pythoncom, and you import it in your example code. The problem is you never actually use pythoncom anywhere in your example code, you only import it. Why give it special mention and then not show its usage?
– Buttons840
Apr 12 '11 at 17:56
9
Why for thesocket.setdefaulttimeout(60)
is? Is it needed for a service, or was it just accidentaly copied from some existing service? :)
– Timur
Sep 10 '11 at 12:42
6
chrisumbel.com/article/windows_services_in_python This one is a similar example but more complete
– csprabala
May 27 '15 at 15:55
|
show 15 more comments
15
After coding this, how do I tell Windows to run this as a service?
– Kit
Sep 19 '10 at 23:44
30
@Kit: run your script with the from the command line with the parameter "install". Then you'll be able to see your application in Windows' Services list, where you can start it, stop it, or set it to start automatically
– Ricardo Reyes
Sep 22 '10 at 12:29
16
You give special mention to pythoncom, and you import it in your example code. The problem is you never actually use pythoncom anywhere in your example code, you only import it. Why give it special mention and then not show its usage?
– Buttons840
Apr 12 '11 at 17:56
9
Why for thesocket.setdefaulttimeout(60)
is? Is it needed for a service, or was it just accidentaly copied from some existing service? :)
– Timur
Sep 10 '11 at 12:42
6
chrisumbel.com/article/windows_services_in_python This one is a similar example but more complete
– csprabala
May 27 '15 at 15:55
15
15
After coding this, how do I tell Windows to run this as a service?
– Kit
Sep 19 '10 at 23:44
After coding this, how do I tell Windows to run this as a service?
– Kit
Sep 19 '10 at 23:44
30
30
@Kit: run your script with the from the command line with the parameter "install". Then you'll be able to see your application in Windows' Services list, where you can start it, stop it, or set it to start automatically
– Ricardo Reyes
Sep 22 '10 at 12:29
@Kit: run your script with the from the command line with the parameter "install". Then you'll be able to see your application in Windows' Services list, where you can start it, stop it, or set it to start automatically
– Ricardo Reyes
Sep 22 '10 at 12:29
16
16
You give special mention to pythoncom, and you import it in your example code. The problem is you never actually use pythoncom anywhere in your example code, you only import it. Why give it special mention and then not show its usage?
– Buttons840
Apr 12 '11 at 17:56
You give special mention to pythoncom, and you import it in your example code. The problem is you never actually use pythoncom anywhere in your example code, you only import it. Why give it special mention and then not show its usage?
– Buttons840
Apr 12 '11 at 17:56
9
9
Why for the
socket.setdefaulttimeout(60)
is? Is it needed for a service, or was it just accidentaly copied from some existing service? :)– Timur
Sep 10 '11 at 12:42
Why for the
socket.setdefaulttimeout(60)
is? Is it needed for a service, or was it just accidentaly copied from some existing service? :)– Timur
Sep 10 '11 at 12:42
6
6
chrisumbel.com/article/windows_services_in_python This one is a similar example but more complete
– csprabala
May 27 '15 at 15:55
chrisumbel.com/article/windows_services_in_python This one is a similar example but more complete
– csprabala
May 27 '15 at 15:55
|
show 15 more comments
up vote
31
down vote
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?
I stumbled across the wonderful Non-sucking Service Manager, 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.
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.
Any luck? I'm building a very simple site for a client and don't need to use the whole Apache stack. Also building the service by myself has sounded like an invite for trouble too, as I have read from other comments.
– Jaran
Aug 17 '14 at 12:25
Yes, this works and it is very easy to do. You just give the path and arguments for the script. I was able to get mine to run with out a console just in case someone ends up with a console window somehow.
– kmcguire
Sep 9 '14 at 13:44
While this apparently works, there are other difficulties especially when you "don't need to use the whole Apache stack": gunicorn for example doesn't run on Windows yet, which actually was the showstopper for me.
– mknaf
Sep 9 '14 at 19:15
2
The trick here is to run python.exe as a service and your python script as the parameter: like "nssm install MyServiceName c:python27python.exe c:tempmyscript.py"
– poleguy
Nov 23 '15 at 23:22
Works great! On a system with multiple virtual environments, the path can reference the Python interpreter exe in the Scripts directory of the desired virtual environment. It seems likenew-service
in PowerShell should be able to do this, but starting (and monitoring) a script as a service evidently involves a lot more details, which nssm takes care of very nicely.
– Fred Schleifer
Dec 22 '15 at 7:23
add a comment |
up vote
31
down vote
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?
I stumbled across the wonderful Non-sucking Service Manager, 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.
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.
Any luck? I'm building a very simple site for a client and don't need to use the whole Apache stack. Also building the service by myself has sounded like an invite for trouble too, as I have read from other comments.
– Jaran
Aug 17 '14 at 12:25
Yes, this works and it is very easy to do. You just give the path and arguments for the script. I was able to get mine to run with out a console just in case someone ends up with a console window somehow.
– kmcguire
Sep 9 '14 at 13:44
While this apparently works, there are other difficulties especially when you "don't need to use the whole Apache stack": gunicorn for example doesn't run on Windows yet, which actually was the showstopper for me.
– mknaf
Sep 9 '14 at 19:15
2
The trick here is to run python.exe as a service and your python script as the parameter: like "nssm install MyServiceName c:python27python.exe c:tempmyscript.py"
– poleguy
Nov 23 '15 at 23:22
Works great! On a system with multiple virtual environments, the path can reference the Python interpreter exe in the Scripts directory of the desired virtual environment. It seems likenew-service
in PowerShell should be able to do this, but starting (and monitoring) a script as a service evidently involves a lot more details, which nssm takes care of very nicely.
– Fred Schleifer
Dec 22 '15 at 7:23
add a comment |
up vote
31
down vote
up vote
31
down vote
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?
I stumbled across the wonderful Non-sucking Service Manager, 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.
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.
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?
I stumbled across the wonderful Non-sucking Service Manager, 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.
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.
answered Jul 28 '14 at 13:41
mknaf
582613
582613
Any luck? I'm building a very simple site for a client and don't need to use the whole Apache stack. Also building the service by myself has sounded like an invite for trouble too, as I have read from other comments.
– Jaran
Aug 17 '14 at 12:25
Yes, this works and it is very easy to do. You just give the path and arguments for the script. I was able to get mine to run with out a console just in case someone ends up with a console window somehow.
– kmcguire
Sep 9 '14 at 13:44
While this apparently works, there are other difficulties especially when you "don't need to use the whole Apache stack": gunicorn for example doesn't run on Windows yet, which actually was the showstopper for me.
– mknaf
Sep 9 '14 at 19:15
2
The trick here is to run python.exe as a service and your python script as the parameter: like "nssm install MyServiceName c:python27python.exe c:tempmyscript.py"
– poleguy
Nov 23 '15 at 23:22
Works great! On a system with multiple virtual environments, the path can reference the Python interpreter exe in the Scripts directory of the desired virtual environment. It seems likenew-service
in PowerShell should be able to do this, but starting (and monitoring) a script as a service evidently involves a lot more details, which nssm takes care of very nicely.
– Fred Schleifer
Dec 22 '15 at 7:23
add a comment |
Any luck? I'm building a very simple site for a client and don't need to use the whole Apache stack. Also building the service by myself has sounded like an invite for trouble too, as I have read from other comments.
– Jaran
Aug 17 '14 at 12:25
Yes, this works and it is very easy to do. You just give the path and arguments for the script. I was able to get mine to run with out a console just in case someone ends up with a console window somehow.
– kmcguire
Sep 9 '14 at 13:44
While this apparently works, there are other difficulties especially when you "don't need to use the whole Apache stack": gunicorn for example doesn't run on Windows yet, which actually was the showstopper for me.
– mknaf
Sep 9 '14 at 19:15
2
The trick here is to run python.exe as a service and your python script as the parameter: like "nssm install MyServiceName c:python27python.exe c:tempmyscript.py"
– poleguy
Nov 23 '15 at 23:22
Works great! On a system with multiple virtual environments, the path can reference the Python interpreter exe in the Scripts directory of the desired virtual environment. It seems likenew-service
in PowerShell should be able to do this, but starting (and monitoring) a script as a service evidently involves a lot more details, which nssm takes care of very nicely.
– Fred Schleifer
Dec 22 '15 at 7:23
Any luck? I'm building a very simple site for a client and don't need to use the whole Apache stack. Also building the service by myself has sounded like an invite for trouble too, as I have read from other comments.
– Jaran
Aug 17 '14 at 12:25
Any luck? I'm building a very simple site for a client and don't need to use the whole Apache stack. Also building the service by myself has sounded like an invite for trouble too, as I have read from other comments.
– Jaran
Aug 17 '14 at 12:25
Yes, this works and it is very easy to do. You just give the path and arguments for the script. I was able to get mine to run with out a console just in case someone ends up with a console window somehow.
– kmcguire
Sep 9 '14 at 13:44
Yes, this works and it is very easy to do. You just give the path and arguments for the script. I was able to get mine to run with out a console just in case someone ends up with a console window somehow.
– kmcguire
Sep 9 '14 at 13:44
While this apparently works, there are other difficulties especially when you "don't need to use the whole Apache stack": gunicorn for example doesn't run on Windows yet, which actually was the showstopper for me.
– mknaf
Sep 9 '14 at 19:15
While this apparently works, there are other difficulties especially when you "don't need to use the whole Apache stack": gunicorn for example doesn't run on Windows yet, which actually was the showstopper for me.
– mknaf
Sep 9 '14 at 19:15
2
2
The trick here is to run python.exe as a service and your python script as the parameter: like "nssm install MyServiceName c:python27python.exe c:tempmyscript.py"
– poleguy
Nov 23 '15 at 23:22
The trick here is to run python.exe as a service and your python script as the parameter: like "nssm install MyServiceName c:python27python.exe c:tempmyscript.py"
– poleguy
Nov 23 '15 at 23:22
Works great! On a system with multiple virtual environments, the path can reference the Python interpreter exe in the Scripts directory of the desired virtual environment. It seems like
new-service
in PowerShell should be able to do this, but starting (and monitoring) a script as a service evidently involves a lot more details, which nssm takes care of very nicely.– Fred Schleifer
Dec 22 '15 at 7:23
Works great! On a system with multiple virtual environments, the path can reference the Python interpreter exe in the Scripts directory of the desired virtual environment. It seems like
new-service
in PowerShell should be able to do this, but starting (and monitoring) a script as a service evidently involves a lot more details, which nssm takes care of very nicely.– Fred Schleifer
Dec 22 '15 at 7:23
add a comment |
up vote
24
down vote
There are a couple alternatives for installing as a service virtually any Windows executable.
Method 1: Use instsrv and srvany from rktools.exe
For Windows Home Server or Windows Server 2003 (works with WinXP too), the Windows Server 2003 Resource Kit Tools comes with utilities that can be used in tandem for this, called instsrv.exe and srvany.exe. See this Microsoft KB article KB137890 for details on how to use these utils.
For Windows Home Server, there is a great user friendly wrapper for these utilities named aptly "Any Service Installer".
Method 2: Use ServiceInstaller for Windows NT
There is another alternative using ServiceInstaller for Windows NT (download-able here) with python instructions available. 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.
Installing a Python script
Run ServiceInstaller to create a new
service. (In this example, it is
assumed that python is installed at
c:python25)
Service Name : PythonTest
Display Name : PythonTest
Startup : Manual (or whatever you like)
Dependencies : (Leave blank or fill to fit your needs)
Executable : c:python25python.exe
Arguments : c:path_to_your_python_scripttest.py
Working Directory : c:path_to_your_python_script
After installing, open the Control
Panel's Services applet, select and
start the PythonTest service.
After my initial answer, I noticed there were closely related Q&A already posted on SO. See also:
Can I run a Python script as a service (in Windows)? How?
How do I make Windows aware of a service I have written in Python?
I just noticed there are other similar Q&A already: stackoverflow.com/questions/32404/… stackoverflow.com/questions/34328/…
– popcnt
Feb 28 '09 at 8:44
Service Installer doesn't working on a 64 bit architecture so option 1 becomes the goto option.
– Noah Campbell
Jun 10 '11 at 20:02
The above link to ServiceInstaller no longer works. I found it here: sites.google.com/site/conort/…
– LarsH
Nov 14 '11 at 17:25
1
off note, I don't thinkNT
would be necessarily "contrary" to the name, at least not in programmer-folk speech. It just refers to the "NT architecture", as opposed to the "NT brand". That said, according to talk on wikipedia this is up to debate, since "it's not an official Microsoft term", but there is nevertheless a tradition with this line of thinking.
– n611x007
Jul 9 '14 at 8:30
add a comment |
up vote
24
down vote
There are a couple alternatives for installing as a service virtually any Windows executable.
Method 1: Use instsrv and srvany from rktools.exe
For Windows Home Server or Windows Server 2003 (works with WinXP too), the Windows Server 2003 Resource Kit Tools comes with utilities that can be used in tandem for this, called instsrv.exe and srvany.exe. See this Microsoft KB article KB137890 for details on how to use these utils.
For Windows Home Server, there is a great user friendly wrapper for these utilities named aptly "Any Service Installer".
Method 2: Use ServiceInstaller for Windows NT
There is another alternative using ServiceInstaller for Windows NT (download-able here) with python instructions available. 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.
Installing a Python script
Run ServiceInstaller to create a new
service. (In this example, it is
assumed that python is installed at
c:python25)
Service Name : PythonTest
Display Name : PythonTest
Startup : Manual (or whatever you like)
Dependencies : (Leave blank or fill to fit your needs)
Executable : c:python25python.exe
Arguments : c:path_to_your_python_scripttest.py
Working Directory : c:path_to_your_python_script
After installing, open the Control
Panel's Services applet, select and
start the PythonTest service.
After my initial answer, I noticed there were closely related Q&A already posted on SO. See also:
Can I run a Python script as a service (in Windows)? How?
How do I make Windows aware of a service I have written in Python?
I just noticed there are other similar Q&A already: stackoverflow.com/questions/32404/… stackoverflow.com/questions/34328/…
– popcnt
Feb 28 '09 at 8:44
Service Installer doesn't working on a 64 bit architecture so option 1 becomes the goto option.
– Noah Campbell
Jun 10 '11 at 20:02
The above link to ServiceInstaller no longer works. I found it here: sites.google.com/site/conort/…
– LarsH
Nov 14 '11 at 17:25
1
off note, I don't thinkNT
would be necessarily "contrary" to the name, at least not in programmer-folk speech. It just refers to the "NT architecture", as opposed to the "NT brand". That said, according to talk on wikipedia this is up to debate, since "it's not an official Microsoft term", but there is nevertheless a tradition with this line of thinking.
– n611x007
Jul 9 '14 at 8:30
add a comment |
up vote
24
down vote
up vote
24
down vote
There are a couple alternatives for installing as a service virtually any Windows executable.
Method 1: Use instsrv and srvany from rktools.exe
For Windows Home Server or Windows Server 2003 (works with WinXP too), the Windows Server 2003 Resource Kit Tools comes with utilities that can be used in tandem for this, called instsrv.exe and srvany.exe. See this Microsoft KB article KB137890 for details on how to use these utils.
For Windows Home Server, there is a great user friendly wrapper for these utilities named aptly "Any Service Installer".
Method 2: Use ServiceInstaller for Windows NT
There is another alternative using ServiceInstaller for Windows NT (download-able here) with python instructions available. 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.
Installing a Python script
Run ServiceInstaller to create a new
service. (In this example, it is
assumed that python is installed at
c:python25)
Service Name : PythonTest
Display Name : PythonTest
Startup : Manual (or whatever you like)
Dependencies : (Leave blank or fill to fit your needs)
Executable : c:python25python.exe
Arguments : c:path_to_your_python_scripttest.py
Working Directory : c:path_to_your_python_script
After installing, open the Control
Panel's Services applet, select and
start the PythonTest service.
After my initial answer, I noticed there were closely related Q&A already posted on SO. See also:
Can I run a Python script as a service (in Windows)? How?
How do I make Windows aware of a service I have written in Python?
There are a couple alternatives for installing as a service virtually any Windows executable.
Method 1: Use instsrv and srvany from rktools.exe
For Windows Home Server or Windows Server 2003 (works with WinXP too), the Windows Server 2003 Resource Kit Tools comes with utilities that can be used in tandem for this, called instsrv.exe and srvany.exe. See this Microsoft KB article KB137890 for details on how to use these utils.
For Windows Home Server, there is a great user friendly wrapper for these utilities named aptly "Any Service Installer".
Method 2: Use ServiceInstaller for Windows NT
There is another alternative using ServiceInstaller for Windows NT (download-able here) with python instructions available. 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.
Installing a Python script
Run ServiceInstaller to create a new
service. (In this example, it is
assumed that python is installed at
c:python25)
Service Name : PythonTest
Display Name : PythonTest
Startup : Manual (or whatever you like)
Dependencies : (Leave blank or fill to fit your needs)
Executable : c:python25python.exe
Arguments : c:path_to_your_python_scripttest.py
Working Directory : c:path_to_your_python_script
After installing, open the Control
Panel's Services applet, select and
start the PythonTest service.
After my initial answer, I noticed there were closely related Q&A already posted on SO. See also:
Can I run a Python script as a service (in Windows)? How?
How do I make Windows aware of a service I have written in Python?
edited May 23 '17 at 11:55
Community♦
11
11
answered Feb 28 '09 at 8:30
popcnt
3,26311114
3,26311114
I just noticed there are other similar Q&A already: stackoverflow.com/questions/32404/… stackoverflow.com/questions/34328/…
– popcnt
Feb 28 '09 at 8:44
Service Installer doesn't working on a 64 bit architecture so option 1 becomes the goto option.
– Noah Campbell
Jun 10 '11 at 20:02
The above link to ServiceInstaller no longer works. I found it here: sites.google.com/site/conort/…
– LarsH
Nov 14 '11 at 17:25
1
off note, I don't thinkNT
would be necessarily "contrary" to the name, at least not in programmer-folk speech. It just refers to the "NT architecture", as opposed to the "NT brand". That said, according to talk on wikipedia this is up to debate, since "it's not an official Microsoft term", but there is nevertheless a tradition with this line of thinking.
– n611x007
Jul 9 '14 at 8:30
add a comment |
I just noticed there are other similar Q&A already: stackoverflow.com/questions/32404/… stackoverflow.com/questions/34328/…
– popcnt
Feb 28 '09 at 8:44
Service Installer doesn't working on a 64 bit architecture so option 1 becomes the goto option.
– Noah Campbell
Jun 10 '11 at 20:02
The above link to ServiceInstaller no longer works. I found it here: sites.google.com/site/conort/…
– LarsH
Nov 14 '11 at 17:25
1
off note, I don't thinkNT
would be necessarily "contrary" to the name, at least not in programmer-folk speech. It just refers to the "NT architecture", as opposed to the "NT brand". That said, according to talk on wikipedia this is up to debate, since "it's not an official Microsoft term", but there is nevertheless a tradition with this line of thinking.
– n611x007
Jul 9 '14 at 8:30
I just noticed there are other similar Q&A already: stackoverflow.com/questions/32404/… stackoverflow.com/questions/34328/…
– popcnt
Feb 28 '09 at 8:44
I just noticed there are other similar Q&A already: stackoverflow.com/questions/32404/… stackoverflow.com/questions/34328/…
– popcnt
Feb 28 '09 at 8:44
Service Installer doesn't working on a 64 bit architecture so option 1 becomes the goto option.
– Noah Campbell
Jun 10 '11 at 20:02
Service Installer doesn't working on a 64 bit architecture so option 1 becomes the goto option.
– Noah Campbell
Jun 10 '11 at 20:02
The above link to ServiceInstaller no longer works. I found it here: sites.google.com/site/conort/…
– LarsH
Nov 14 '11 at 17:25
The above link to ServiceInstaller no longer works. I found it here: sites.google.com/site/conort/…
– LarsH
Nov 14 '11 at 17:25
1
1
off note, I don't think
NT
would be necessarily "contrary" to the name, at least not in programmer-folk speech. It just refers to the "NT architecture", as opposed to the "NT brand". That said, according to talk on wikipedia this is up to debate, since "it's not an official Microsoft term", but there is nevertheless a tradition with this line of thinking.– n611x007
Jul 9 '14 at 8:30
off note, I don't think
NT
would be necessarily "contrary" to the name, at least not in programmer-folk speech. It just refers to the "NT architecture", as opposed to the "NT brand". That said, according to talk on wikipedia this is up to debate, since "it's not an official Microsoft term", but there is nevertheless a tradition with this line of thinking.– n611x007
Jul 9 '14 at 8:30
add a comment |
up vote
17
down vote
The simplest way to achive this is to use native command sc.exe:
sc create PythonApp binPath= "C:Python34Python.exe --C:tmppythonscript.py"
- https://technet.microsoft.com/en-us/library/cc990289(v=ws.11).aspx
- creating a service with sc.exe; how to pass in context parameters
add a comment |
up vote
17
down vote
The simplest way to achive this is to use native command sc.exe:
sc create PythonApp binPath= "C:Python34Python.exe --C:tmppythonscript.py"
- https://technet.microsoft.com/en-us/library/cc990289(v=ws.11).aspx
- creating a service with sc.exe; how to pass in context parameters
add a comment |
up vote
17
down vote
up vote
17
down vote
The simplest way to achive this is to use native command sc.exe:
sc create PythonApp binPath= "C:Python34Python.exe --C:tmppythonscript.py"
- https://technet.microsoft.com/en-us/library/cc990289(v=ws.11).aspx
- creating a service with sc.exe; how to pass in context parameters
The simplest way to achive this is to use native command sc.exe:
sc create PythonApp binPath= "C:Python34Python.exe --C:tmppythonscript.py"
- https://technet.microsoft.com/en-us/library/cc990289(v=ws.11).aspx
- creating a service with sc.exe; how to pass in context parameters
edited May 23 '17 at 12:02
Community♦
11
11
answered Dec 7 '16 at 12:23
pyOwner
30526
30526
add a comment |
add a comment |
up vote
12
down vote
The simplest way is to use the: NSSM - the Non-Sucking Service Manager:
1 - make download on https://nssm.cc/download
2 - install the python program as a service: Win prompt as admin
c:>nssm.exe install WinService
3 - On NSSM´s console:
path: C:Python27Python27.exe
Startup directory: C:Python27
Arguments: c:WinService.py
4 - check the created services on services.msc
add a comment |
up vote
12
down vote
The simplest way is to use the: NSSM - the Non-Sucking Service Manager:
1 - make download on https://nssm.cc/download
2 - install the python program as a service: Win prompt as admin
c:>nssm.exe install WinService
3 - On NSSM´s console:
path: C:Python27Python27.exe
Startup directory: C:Python27
Arguments: c:WinService.py
4 - check the created services on services.msc
add a comment |
up vote
12
down vote
up vote
12
down vote
The simplest way is to use the: NSSM - the Non-Sucking Service Manager:
1 - make download on https://nssm.cc/download
2 - install the python program as a service: Win prompt as admin
c:>nssm.exe install WinService
3 - On NSSM´s console:
path: C:Python27Python27.exe
Startup directory: C:Python27
Arguments: c:WinService.py
4 - check the created services on services.msc
The simplest way is to use the: NSSM - the Non-Sucking Service Manager:
1 - make download on https://nssm.cc/download
2 - install the python program as a service: Win prompt as admin
c:>nssm.exe install WinService
3 - On NSSM´s console:
path: C:Python27Python27.exe
Startup directory: C:Python27
Arguments: c:WinService.py
4 - check the created services on services.msc
answered Sep 27 '17 at 14:05
Adriano R P L
12113
12113
add a comment |
add a comment |
up vote
9
down vote
Step by step explanation how to make it work :
1- First create a python file according to the basic skeleton mentioned above. And save it to a path for example : "c:PythonFilesAppServerSvc.py"
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):
# Your business logic or call to any class should be here
# this time it creates a text.txt and writes Test Service in a daily manner
f = open('C:\test.txt', 'a')
rc = None
while rc != win32event.WAIT_OBJECT_0:
f.write('Test Service n')
f.flush()
# block for 24*60*60 seconds and wait for a stop event
# it is used for a one-day loop
rc = win32event.WaitForSingleObject(self.hWaitStop, 24 * 60 * 60 * 1000)
f.write('shut down n')
f.close()
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(AppServerSvc)
2 - On this step we should register our service.
Run command prompt as administrator and type as:
sc create TestService binpath= "C:Python36Python.exe c:PythonFilesAppServerSvc.py" DisplayName= "TestService" start= auto
the first argument of binpath is the path of python.exe
second argument of binpath is the path of your python file that we created already
Don't miss that you should put one space after every "=" sign.
Then if everything is ok, you should see
[SC] CreateService SUCCESS
Now your python service is installed as windows service now. You can see it in Service Manager and registry under :
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesTestService
3- Ok now. You can start your service on service manager.
You can execute every python file that provides this service skeleton.
add a comment |
up vote
9
down vote
Step by step explanation how to make it work :
1- First create a python file according to the basic skeleton mentioned above. And save it to a path for example : "c:PythonFilesAppServerSvc.py"
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):
# Your business logic or call to any class should be here
# this time it creates a text.txt and writes Test Service in a daily manner
f = open('C:\test.txt', 'a')
rc = None
while rc != win32event.WAIT_OBJECT_0:
f.write('Test Service n')
f.flush()
# block for 24*60*60 seconds and wait for a stop event
# it is used for a one-day loop
rc = win32event.WaitForSingleObject(self.hWaitStop, 24 * 60 * 60 * 1000)
f.write('shut down n')
f.close()
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(AppServerSvc)
2 - On this step we should register our service.
Run command prompt as administrator and type as:
sc create TestService binpath= "C:Python36Python.exe c:PythonFilesAppServerSvc.py" DisplayName= "TestService" start= auto
the first argument of binpath is the path of python.exe
second argument of binpath is the path of your python file that we created already
Don't miss that you should put one space after every "=" sign.
Then if everything is ok, you should see
[SC] CreateService SUCCESS
Now your python service is installed as windows service now. You can see it in Service Manager and registry under :
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesTestService
3- Ok now. You can start your service on service manager.
You can execute every python file that provides this service skeleton.
add a comment |
up vote
9
down vote
up vote
9
down vote
Step by step explanation how to make it work :
1- First create a python file according to the basic skeleton mentioned above. And save it to a path for example : "c:PythonFilesAppServerSvc.py"
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):
# Your business logic or call to any class should be here
# this time it creates a text.txt and writes Test Service in a daily manner
f = open('C:\test.txt', 'a')
rc = None
while rc != win32event.WAIT_OBJECT_0:
f.write('Test Service n')
f.flush()
# block for 24*60*60 seconds and wait for a stop event
# it is used for a one-day loop
rc = win32event.WaitForSingleObject(self.hWaitStop, 24 * 60 * 60 * 1000)
f.write('shut down n')
f.close()
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(AppServerSvc)
2 - On this step we should register our service.
Run command prompt as administrator and type as:
sc create TestService binpath= "C:Python36Python.exe c:PythonFilesAppServerSvc.py" DisplayName= "TestService" start= auto
the first argument of binpath is the path of python.exe
second argument of binpath is the path of your python file that we created already
Don't miss that you should put one space after every "=" sign.
Then if everything is ok, you should see
[SC] CreateService SUCCESS
Now your python service is installed as windows service now. You can see it in Service Manager and registry under :
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesTestService
3- Ok now. You can start your service on service manager.
You can execute every python file that provides this service skeleton.
Step by step explanation how to make it work :
1- First create a python file according to the basic skeleton mentioned above. And save it to a path for example : "c:PythonFilesAppServerSvc.py"
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):
# Your business logic or call to any class should be here
# this time it creates a text.txt and writes Test Service in a daily manner
f = open('C:\test.txt', 'a')
rc = None
while rc != win32event.WAIT_OBJECT_0:
f.write('Test Service n')
f.flush()
# block for 24*60*60 seconds and wait for a stop event
# it is used for a one-day loop
rc = win32event.WaitForSingleObject(self.hWaitStop, 24 * 60 * 60 * 1000)
f.write('shut down n')
f.close()
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(AppServerSvc)
2 - On this step we should register our service.
Run command prompt as administrator and type as:
sc create TestService binpath= "C:Python36Python.exe c:PythonFilesAppServerSvc.py" DisplayName= "TestService" start= auto
the first argument of binpath is the path of python.exe
second argument of binpath is the path of your python file that we created already
Don't miss that you should put one space after every "=" sign.
Then if everything is ok, you should see
[SC] CreateService SUCCESS
Now your python service is installed as windows service now. You can see it in Service Manager and registry under :
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesTestService
3- Ok now. You can start your service on service manager.
You can execute every python file that provides this service skeleton.
answered Jun 29 '17 at 8:37
Seckin Sanli
9112
9112
add a comment |
add a comment |
up vote
1
down vote
I started hosting as a service with pywin32.
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.
Error messages were:
Error 1053: The service did not respond to the start or control request in a timely fashion.
Error 7009: Timeout (30000 milliseconds) waiting for the <ServiceName> service to connect.
I fought a lot with pywin, but ended up with using NSSM as it was proposed in this answer. It was very easy to migrate to it.
add a comment |
up vote
1
down vote
I started hosting as a service with pywin32.
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.
Error messages were:
Error 1053: The service did not respond to the start or control request in a timely fashion.
Error 7009: Timeout (30000 milliseconds) waiting for the <ServiceName> service to connect.
I fought a lot with pywin, but ended up with using NSSM as it was proposed in this answer. It was very easy to migrate to it.
add a comment |
up vote
1
down vote
up vote
1
down vote
I started hosting as a service with pywin32.
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.
Error messages were:
Error 1053: The service did not respond to the start or control request in a timely fashion.
Error 7009: Timeout (30000 milliseconds) waiting for the <ServiceName> service to connect.
I fought a lot with pywin, but ended up with using NSSM as it was proposed in this answer. It was very easy to migrate to it.
I started hosting as a service with pywin32.
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.
Error messages were:
Error 1053: The service did not respond to the start or control request in a timely fashion.
Error 7009: Timeout (30000 milliseconds) waiting for the <ServiceName> service to connect.
I fought a lot with pywin, but ended up with using NSSM as it was proposed in this answer. It was very easy to migrate to it.
answered Oct 12 at 13:07
flam3
312117
312117
add a comment |
add a comment |
up vote
0
down vote
The accepted answer using win32serviceutil
works but is complicated and makes debugging and changes harder. It is far easier to use NSSM (the Non-Sucking Service Manager). 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:
From an elevated (admin) command prompt you run nssm.exe install NameOfYourService
and you fill-in these options:
path: (the path to python.exe e.g.C:Python27Python.exe
)
Arguments: (the path to your python script, e.g.c:pathtoprogram.py
)
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.
Yes, this is a duplicate of Adriano's answer. I upvoted that answer and tried to edit it but after the edits I was looking at a new answer.
– ndemou
Nov 10 at 15:59
add a comment |
up vote
0
down vote
The accepted answer using win32serviceutil
works but is complicated and makes debugging and changes harder. It is far easier to use NSSM (the Non-Sucking Service Manager). 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:
From an elevated (admin) command prompt you run nssm.exe install NameOfYourService
and you fill-in these options:
path: (the path to python.exe e.g.C:Python27Python.exe
)
Arguments: (the path to your python script, e.g.c:pathtoprogram.py
)
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.
Yes, this is a duplicate of Adriano's answer. I upvoted that answer and tried to edit it but after the edits I was looking at a new answer.
– ndemou
Nov 10 at 15:59
add a comment |
up vote
0
down vote
up vote
0
down vote
The accepted answer using win32serviceutil
works but is complicated and makes debugging and changes harder. It is far easier to use NSSM (the Non-Sucking Service Manager). 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:
From an elevated (admin) command prompt you run nssm.exe install NameOfYourService
and you fill-in these options:
path: (the path to python.exe e.g.C:Python27Python.exe
)
Arguments: (the path to your python script, e.g.c:pathtoprogram.py
)
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.
The accepted answer using win32serviceutil
works but is complicated and makes debugging and changes harder. It is far easier to use NSSM (the Non-Sucking Service Manager). 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:
From an elevated (admin) command prompt you run nssm.exe install NameOfYourService
and you fill-in these options:
path: (the path to python.exe e.g.C:Python27Python.exe
)
Arguments: (the path to your python script, e.g.c:pathtoprogram.py
)
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.
edited Nov 10 at 16:00
answered Nov 10 at 15:52
ndemou
1,61111822
1,61111822
Yes, this is a duplicate of Adriano's answer. I upvoted that answer and tried to edit it but after the edits I was looking at a new answer.
– ndemou
Nov 10 at 15:59
add a comment |
Yes, this is a duplicate of Adriano's answer. I upvoted that answer and tried to edit it but after the edits I was looking at a new answer.
– ndemou
Nov 10 at 15:59
Yes, this is a duplicate of Adriano's answer. I upvoted that answer and tried to edit it but after the edits I was looking at a new answer.
– ndemou
Nov 10 at 15:59
Yes, this is a duplicate of Adriano's answer. I upvoted that answer and tried to edit it but after the edits I was looking at a new answer.
– ndemou
Nov 10 at 15:59
add a comment |
up vote
-2
down vote
pysc: Service Control Manager on Python
Example script to run as a service taken from pythonhosted.org:
from xmlrpc.server import SimpleXMLRPCServer
from pysc import event_stop
class TestServer:
def echo(self, msg):
return msg
if __name__ == '__main__':
server = SimpleXMLRPCServer(('127.0.0.1', 9001))
@event_stop
def stop():
server.server_close()
server.register_instance(TestServer())
server.serve_forever()
Create and start service
import os
import sys
from xmlrpc.client import ServerProxy
import pysc
if __name__ == '__main__':
service_name = 'test_xmlrpc_server'
script_path = os.path.join(
os.path.dirname(__file__), 'xmlrpc_server.py'
)
pysc.create(
service_name=service_name,
cmd=[sys.executable, script_path]
)
pysc.start(service_name)
client = ServerProxy('http://127.0.0.1:9001')
print(client.echo('test scm'))
Stop and delete service
import pysc
service_name = 'test_xmlrpc_server'
pysc.stop(service_name)
pysc.delete(service_name)
pip install pysc
Does anyone know why this got a downvote? It looks like a nice solution.
– Jarrod Chesney
Jul 15 '17 at 13:22
4
I've tried this approach, it doesn't work.
– Jarrod Chesney
Jul 16 '17 at 2:53
add a comment |
up vote
-2
down vote
pysc: Service Control Manager on Python
Example script to run as a service taken from pythonhosted.org:
from xmlrpc.server import SimpleXMLRPCServer
from pysc import event_stop
class TestServer:
def echo(self, msg):
return msg
if __name__ == '__main__':
server = SimpleXMLRPCServer(('127.0.0.1', 9001))
@event_stop
def stop():
server.server_close()
server.register_instance(TestServer())
server.serve_forever()
Create and start service
import os
import sys
from xmlrpc.client import ServerProxy
import pysc
if __name__ == '__main__':
service_name = 'test_xmlrpc_server'
script_path = os.path.join(
os.path.dirname(__file__), 'xmlrpc_server.py'
)
pysc.create(
service_name=service_name,
cmd=[sys.executable, script_path]
)
pysc.start(service_name)
client = ServerProxy('http://127.0.0.1:9001')
print(client.echo('test scm'))
Stop and delete service
import pysc
service_name = 'test_xmlrpc_server'
pysc.stop(service_name)
pysc.delete(service_name)
pip install pysc
Does anyone know why this got a downvote? It looks like a nice solution.
– Jarrod Chesney
Jul 15 '17 at 13:22
4
I've tried this approach, it doesn't work.
– Jarrod Chesney
Jul 16 '17 at 2:53
add a comment |
up vote
-2
down vote
up vote
-2
down vote
pysc: Service Control Manager on Python
Example script to run as a service taken from pythonhosted.org:
from xmlrpc.server import SimpleXMLRPCServer
from pysc import event_stop
class TestServer:
def echo(self, msg):
return msg
if __name__ == '__main__':
server = SimpleXMLRPCServer(('127.0.0.1', 9001))
@event_stop
def stop():
server.server_close()
server.register_instance(TestServer())
server.serve_forever()
Create and start service
import os
import sys
from xmlrpc.client import ServerProxy
import pysc
if __name__ == '__main__':
service_name = 'test_xmlrpc_server'
script_path = os.path.join(
os.path.dirname(__file__), 'xmlrpc_server.py'
)
pysc.create(
service_name=service_name,
cmd=[sys.executable, script_path]
)
pysc.start(service_name)
client = ServerProxy('http://127.0.0.1:9001')
print(client.echo('test scm'))
Stop and delete service
import pysc
service_name = 'test_xmlrpc_server'
pysc.stop(service_name)
pysc.delete(service_name)
pip install pysc
pysc: Service Control Manager on Python
Example script to run as a service taken from pythonhosted.org:
from xmlrpc.server import SimpleXMLRPCServer
from pysc import event_stop
class TestServer:
def echo(self, msg):
return msg
if __name__ == '__main__':
server = SimpleXMLRPCServer(('127.0.0.1', 9001))
@event_stop
def stop():
server.server_close()
server.register_instance(TestServer())
server.serve_forever()
Create and start service
import os
import sys
from xmlrpc.client import ServerProxy
import pysc
if __name__ == '__main__':
service_name = 'test_xmlrpc_server'
script_path = os.path.join(
os.path.dirname(__file__), 'xmlrpc_server.py'
)
pysc.create(
service_name=service_name,
cmd=[sys.executable, script_path]
)
pysc.start(service_name)
client = ServerProxy('http://127.0.0.1:9001')
print(client.echo('test scm'))
Stop and delete service
import pysc
service_name = 'test_xmlrpc_server'
pysc.stop(service_name)
pysc.delete(service_name)
pip install pysc
edited Mar 8 '17 at 14:20
Matt
61.6k18118159
61.6k18118159
answered Mar 3 '17 at 20:29
Seliverstov Maksim
113
113
Does anyone know why this got a downvote? It looks like a nice solution.
– Jarrod Chesney
Jul 15 '17 at 13:22
4
I've tried this approach, it doesn't work.
– Jarrod Chesney
Jul 16 '17 at 2:53
add a comment |
Does anyone know why this got a downvote? It looks like a nice solution.
– Jarrod Chesney
Jul 15 '17 at 13:22
4
I've tried this approach, it doesn't work.
– Jarrod Chesney
Jul 16 '17 at 2:53
Does anyone know why this got a downvote? It looks like a nice solution.
– Jarrod Chesney
Jul 15 '17 at 13:22
Does anyone know why this got a downvote? It looks like a nice solution.
– Jarrod Chesney
Jul 15 '17 at 13:22
4
4
I've tried this approach, it doesn't work.
– Jarrod Chesney
Jul 16 '17 at 2:53
I've tried this approach, it doesn't work.
– Jarrod Chesney
Jul 16 '17 at 2:53
add a comment |
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f32404%2fhow-do-you-run-a-python-script-as-a-service-in-windows%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
2
Check this Windows Service template it uses the win32service API.
– CMS
Feb 28 '09 at 5:52