I l@ve RuBoard |
7.12 Getting the Windows Service Name from Its Long NameCredit: Andy McKay 7.12.1 ProblemYou need to find the actual name of a Windows service from the longer display name, which is all that many programs show you. 7.12.2 SolutionUnfortunately, a Windows service has two names: a real one (to be used in many operations) and a display name (meant for human display). Fortunately, Python helps you translate between them: import win32api
import win32con
def GetShortName(longName):
# Looks up a service's real name from its display name
hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE,
"SYSTEM\\CurrentControlSet\\Services", 0, win32con.KEY_ALL_ACCESS)
num = win32api.RegQueryInfoKey(hkey)[0]
# Loop through the given number of subkeys
for x in range(0, num):
# Find service name; open subkey
svc = win32api.RegEnumKey(hkey, x)
skey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE,
"SYSTEM\\CurrentControlSet\\Services\\%s" % svc,
0, win32con.KEY_ALL_ACCESS)
try:
# Find short name
shortName = str(win32api.RegQueryValueEx(skey, "DisplayName")[0])
if shortName == longName:
return svc
except win32api.error:
# in case there is no key called DisplayName
pass
return None
if _ _name_ _=='_ _main_ _':
assert(GetShortName('Windows Time') == 'W32Time')
assert(GetShortName('FoobarService') == None)
7.12.3 DiscussionMany programs show only the long description (display name) of a Windows Service, such as Windows Time, but you need the actual service name to operate on the service itself (to restart it, for example). This recipe's function loops through the services on a Windows system (2000/NT) as recorded in the registry. For each service, the code opens the registry key and looks inside the key for the DisplayName value. The service's real name is the key name for which the given long-name argument matches the DisplayName value, if any. This recipe also shows how to access the Windows registry from Python as an alternative to the _winreg module in Python's standard library. Mark Hammond's win32all extensions include registry access APIs in the win32api module, and the functionality they expose is richer and more complete than _winreg's. If you have win32all installed (and you should if you use Python for system-administration tasks on Windows machines), you should use it instead of the standard _winreg module to access and modify the Windows registry. 7.12.4 See AlsoDocumentation for win32api and win32con in win32all (http://starship.python.net/crew/mhammond/win32/Downloads.html) or ActivePython (http://www.activestate.com/ActivePython/); Windows API documentation available from Microsoft (http://msdn.microsoft.com); Python Programming on Win32, by Mark Hammond and Andy Robinson (O'Reilly). |
I l@ve RuBoard |