ActiveState Code

Recipe 59872: Manipulating Windows Services


Its easy to mess with Windows Service using Python.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import win32serviceutil

def service_info(action, machine, service):
    if action == 'stop': 
        win32serviceutil.StopService(service, machine)
        print '%s stopped successfully' % service
    elif action == 'start': 
        win32serviceutil.StartService(service, machine)
        print '%s started successfully' % service
    elif action == 'restart': 
        win32serviceutil.RestartService(service, machine)
        print '%s restarted successfully' % service
    elif action == 'status':
        if win32serviceutil.QueryServiceStatus(service, machine)[1] == 4:
            print "%s is running normally" % service 
        else:
            print "%s is *not* running" % service 

if __name__ == '__main__':
    machine = 'cr582427-a'
    service = 'Zope23'
    action = 'start'
    service_info(action, machine, service)

Discussion

This is extremely simple, all thanks to Mark Hammond's win32api. There are many more options available including install and remove service. These are covered in more details in Python Programming on Win32.

Comments

  1. 1. At 7:57 p.m. on 6 aug 2001, Anonymous said:

    Problems changing modes. The code does not test whether or not the service actually changes from one state to another. I don't know if there is some return code that can be associated with the change of the service, but it would help if it was checked.

Sign in to comment