def UnregisterHelpFile(helpFile, helpDesc = None):
"""Unregister a help file in the registry.
helpFile -- the base name of the help file.
helpDesc -- A description for the help file. If None, the helpFile param is used.
"""
key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\Help", 0, win32con.KEY_ALL_ACCESS)
try:
try:
win32api.RegDeleteValue(key, helpFile)
except win32api.error, exc:
import winerror
if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND:
raise
finally:
win32api.RegCloseKey(key)
# Now de-register with Python itself.
if helpDesc is None: helpDesc = helpFile
try:
win32api.RegDeleteKey(GetRootKey(),
BuildDefaultPythonKey() + "\\Help\\%s" % helpDesc)
except win32api.error, exc:
import winerror
if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND:
raise
python类HKEY_LOCAL_MACHINE的实例源码
def _GetRegistryValue(key, val, default = None):
# val is registry value - None for default val.
try:
hkey = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, key)
return win32api.RegQueryValueEx(hkey, val)[0]
except win32api.error:
try:
hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, key)
return win32api.RegQueryValueEx(hkey, val)[0]
except win32api.error:
return default
def ListAllHelpFiles():
ret = []
ret = _ListAllHelpFilesInRoot(win32con.HKEY_LOCAL_MACHINE)
# Ensure we don't get dups.
for item in _ListAllHelpFilesInRoot(win32con.HKEY_CURRENT_USER):
if item not in ret:
ret.append(item)
return ret
def FindTabNanny():
try:
return __import__("tabnanny")
except ImportError:
pass
# OK - not in the standard library - go looking.
filename = "tabnanny.py"
try:
path = win32api.RegQueryValue(win32con.HKEY_LOCAL_MACHINE, "SOFTWARE\\Python\\PythonCore\\%s\\InstallPath" % (sys.winver))
except win32api.error:
print "WARNING - The Python registry does not have an 'InstallPath' setting"
print " The file '%s' can not be located" % (filename)
return None
fname = os.path.join(path, "Tools\\Scripts\\%s" % filename)
try:
os.stat(fname)
except os.error:
print "WARNING - The file '%s' can not be located in path '%s'" % (filename, path)
return None
tabnannyhome, tabnannybase = os.path.split(fname)
tabnannybase = os.path.splitext(tabnannybase)[0]
# Put tab nanny at the top of the path.
sys.path.insert(0, tabnannyhome)
try:
return __import__(tabnannybase)
finally:
# remove the tab-nanny from the path
del sys.path[0]
def LocatePythonServiceExe(exeName = None):
if not exeName and hasattr(sys, "frozen"):
# If py2exe etc calls this with no exeName, default is current exe.
return sys.executable
# Try and find the specified EXE somewhere. If specifically registered,
# use it. Otherwise look down sys.path, and the global PATH environment.
if exeName is None:
if os.path.splitext(win32service.__file__)[0].endswith("_d"):
exeName = "PythonService_d.exe"
else:
exeName = "PythonService.exe"
# See if it exists as specified
if os.path.isfile(exeName): return win32api.GetFullPathName(exeName)
baseName = os.path.splitext(os.path.basename(exeName))[0]
try:
exeName = win32api.RegQueryValue(win32con.HKEY_LOCAL_MACHINE,
"Software\\Python\\%s\\%s" % (baseName, sys.winver))
if os.path.isfile(exeName):
return exeName
raise RuntimeError("The executable '%s' is registered as the Python " \
"service exe, but it does not exist as specified" \
% exeName)
except win32api.error:
# OK - not there - lets go a-searchin'
for path in [sys.prefix] + sys.path:
look = os.path.join(path, exeName)
if os.path.isfile(look):
return win32api.GetFullPathName(look)
# Try the global Path.
try:
return win32api.SearchPath(None, exeName)[0]
except win32api.error:
msg = "%s is not correctly registered\nPlease locate and run %s, and it will self-register\nThen run this service registration process again." % (exeName, exeName)
raise error(msg)
def LocateSpecificServiceExe(serviceName):
# Given the name of a specific service, return the .EXE name _it_ uses
# (which may or may not be the Python Service EXE
hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services\\%s" % (serviceName), 0, win32con.KEY_ALL_ACCESS)
try:
return win32api.RegQueryValueEx(hkey, "ImagePath")[0]
finally:
hkey.Close()
def InstallPythonClassString(pythonClassString, serviceName):
# Now setup our Python specific entries.
if pythonClassString:
key = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\%s\\PythonClass" % serviceName)
try:
win32api.RegSetValue(key, None, win32con.REG_SZ, pythonClassString);
finally:
win32api.RegCloseKey(key)
# Utility functions for Services, to allow persistant properties.
def SetServiceCustomOption(serviceName, option, value):
try:
serviceName = serviceName._svc_name_
except AttributeError:
pass
key = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\%s\\Parameters" % serviceName)
try:
if type(value)==type(0):
win32api.RegSetValueEx(key, option, 0, win32con.REG_DWORD, value);
else:
win32api.RegSetValueEx(key, option, 0, win32con.REG_SZ, value);
finally:
win32api.RegCloseKey(key)
def GetServiceCustomOption(serviceName, option, defaultValue = None):
# First param may also be a service class/instance.
# This allows services to pass "self"
try:
serviceName = serviceName._svc_name_
except AttributeError:
pass
key = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\%s\\Parameters" % serviceName)
try:
try:
return win32api.RegQueryValueEx(key, option)[0]
except win32api.error: # No value.
return defaultValue
finally:
win32api.RegCloseKey(key)
def _find_localserver_exe(mustfind):
if not sys.platform.startswith("win32"):
return sys.executable
if pythoncom.__file__.find("_d") < 0:
exeBaseName = "pythonw.exe"
else:
exeBaseName = "pythonw_d.exe"
# First see if in the same directory as this .EXE
exeName = os.path.join( os.path.split(sys.executable)[0], exeBaseName )
if not os.path.exists(exeName):
# See if in our sys.prefix directory
exeName = os.path.join( sys.prefix, exeBaseName )
if not os.path.exists(exeName):
# See if in our sys.prefix/pcbuild directory (for developers)
if "64 bit" in sys.version:
exeName = os.path.join( sys.prefix, "PCbuild", "amd64", exeBaseName )
else:
exeName = os.path.join( sys.prefix, "PCbuild", exeBaseName )
if not os.path.exists(exeName):
# See if the registry has some info.
try:
key = "SOFTWARE\\Python\\PythonCore\\%s\\InstallPath" % sys.winver
path = win32api.RegQueryValue( win32con.HKEY_LOCAL_MACHINE, key )
exeName = os.path.join( path, exeBaseName )
except (AttributeError,win32api.error):
pass
if not os.path.exists(exeName):
if mustfind:
raise RuntimeError("Can not locate the program '%s'" % exeBaseName)
return None
return exeName
def _GetRegistryValue(key, val, default = None):
# val is registry value - None for default val.
try:
hkey = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, key)
return win32api.RegQueryValueEx(hkey, val)[0]
except win32api.error:
try:
hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, key)
return win32api.RegQueryValueEx(hkey, val)[0]
except win32api.error:
return default
def ListAllHelpFiles():
ret = []
ret = _ListAllHelpFilesInRoot(win32con.HKEY_LOCAL_MACHINE)
# Ensure we don't get dups.
for item in _ListAllHelpFilesInRoot(win32con.HKEY_CURRENT_USER):
if item not in ret:
ret.append(item)
return ret
def FindTabNanny():
try:
return __import__("tabnanny")
except ImportError:
pass
# OK - not in the standard library - go looking.
filename = "tabnanny.py"
try:
path = win32api.RegQueryValue(win32con.HKEY_LOCAL_MACHINE, "SOFTWARE\\Python\\PythonCore\\%s\\InstallPath" % (sys.winver))
except win32api.error:
print("WARNING - The Python registry does not have an 'InstallPath' setting")
print(" The file '%s' can not be located" % (filename))
return None
fname = os.path.join(path, "Tools\\Scripts\\%s" % filename)
try:
os.stat(fname)
except os.error:
print("WARNING - The file '%s' can not be located in path '%s'" % (filename, path))
return None
tabnannyhome, tabnannybase = os.path.split(fname)
tabnannybase = os.path.splitext(tabnannybase)[0]
# Put tab nanny at the top of the path.
sys.path.insert(0, tabnannyhome)
try:
return __import__(tabnannybase)
finally:
# remove the tab-nanny from the path
del sys.path[0]
def FormatMessage( eventLogRecord, logType="Application" ):
"""Given a tuple from ReadEventLog, and optionally where the event
record came from, load the message, and process message inserts.
Note that this function may raise win32api.error. See also the
function SafeFormatMessage which will return None if the message can
not be processed.
"""
# From the event log source name, we know the name of the registry
# key to look under for the name of the message DLL that contains
# the messages we need to extract with FormatMessage. So first get
# the event log source name...
keyName = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" % (logType, eventLogRecord.SourceName)
# Now open this key and get the EventMessageFile value, which is
# the name of the message DLL.
handle = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, keyName)
try:
dllNames = win32api.RegQueryValueEx(handle, "EventMessageFile")[0].split(";")
# Win2k etc appear to allow multiple DLL names
data = None
for dllName in dllNames:
try:
# Expand environment variable strings in the message DLL path name,
# in case any are there.
dllName = win32api.ExpandEnvironmentStrings(dllName)
dllHandle = win32api.LoadLibraryEx(dllName, 0, win32con.LOAD_LIBRARY_AS_DATAFILE)
try:
data = win32api.FormatMessageW(win32con.FORMAT_MESSAGE_FROM_HMODULE,
dllHandle, eventLogRecord.EventID, langid, eventLogRecord.StringInserts)
finally:
win32api.FreeLibrary(dllHandle)
except win32api.error:
pass # Not in this DLL - try the next
if data is not None:
break
finally:
win32api.RegCloseKey(handle)
return data or '' # Don't want "None" ever being returned.
def UnregisterHelpFile(helpFile, helpDesc = None):
"""Unregister a help file in the registry.
helpFile -- the base name of the help file.
helpDesc -- A description for the help file. If None, the helpFile param is used.
"""
key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\Help", 0, win32con.KEY_ALL_ACCESS)
try:
try:
win32api.RegDeleteValue(key, helpFile)
except win32api.error as exc:
import winerror
if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND:
raise
finally:
win32api.RegCloseKey(key)
# Now de-register with Python itself.
if helpDesc is None: helpDesc = helpFile
try:
win32api.RegDeleteKey(GetRootKey(),
BuildDefaultPythonKey() + "\\Help\\%s" % helpDesc)
except win32api.error as exc:
import winerror
if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND:
raise
def LocatePythonServiceExe(exeName = None):
if not exeName and hasattr(sys, "frozen"):
# If py2exe etc calls this with no exeName, default is current exe.
return sys.executable
# Try and find the specified EXE somewhere. If specifically registered,
# use it. Otherwise look down sys.path, and the global PATH environment.
if exeName is None:
if os.path.splitext(win32service.__file__)[0].endswith("_d"):
exeName = "PythonService_d.exe"
else:
exeName = "PythonService.exe"
# See if it exists as specified
if os.path.isfile(exeName): return win32api.GetFullPathName(exeName)
baseName = os.path.splitext(os.path.basename(exeName))[0]
try:
exeName = win32api.RegQueryValue(win32con.HKEY_LOCAL_MACHINE,
"Software\\Python\\%s\\%s" % (baseName, sys.winver))
if os.path.isfile(exeName):
return exeName
raise RuntimeError("The executable '%s' is registered as the Python " \
"service exe, but it does not exist as specified" \
% exeName)
except win32api.error:
# OK - not there - lets go a-searchin'
for path in [sys.prefix] + sys.path:
look = os.path.join(path, exeName)
if os.path.isfile(look):
return win32api.GetFullPathName(look)
# Try the global Path.
try:
return win32api.SearchPath(None, exeName)[0]
except win32api.error:
msg = "%s is not correctly registered\nPlease locate and run %s, and it will self-register\nThen run this service registration process again." % (exeName, exeName)
raise error(msg)
def LocateSpecificServiceExe(serviceName):
# Given the name of a specific service, return the .EXE name _it_ uses
# (which may or may not be the Python Service EXE
hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services\\%s" % (serviceName), 0, win32con.KEY_ALL_ACCESS)
try:
return win32api.RegQueryValueEx(hkey, "ImagePath")[0]
finally:
hkey.Close()
def InstallPythonClassString(pythonClassString, serviceName):
# Now setup our Python specific entries.
if pythonClassString:
key = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\%s\\PythonClass" % serviceName)
try:
win32api.RegSetValue(key, None, win32con.REG_SZ, pythonClassString);
finally:
win32api.RegCloseKey(key)
# Utility functions for Services, to allow persistant properties.
def SetServiceCustomOption(serviceName, option, value):
try:
serviceName = serviceName._svc_name_
except AttributeError:
pass
key = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\%s\\Parameters" % serviceName)
try:
if type(value)==type(0):
win32api.RegSetValueEx(key, option, 0, win32con.REG_DWORD, value);
else:
win32api.RegSetValueEx(key, option, 0, win32con.REG_SZ, value);
finally:
win32api.RegCloseKey(key)
def GetServiceCustomOption(serviceName, option, defaultValue = None):
# First param may also be a service class/instance.
# This allows services to pass "self"
try:
serviceName = serviceName._svc_name_
except AttributeError:
pass
key = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\%s\\Parameters" % serviceName)
try:
try:
return win32api.RegQueryValueEx(key, option)[0]
except win32api.error: # No value.
return defaultValue
finally:
win32api.RegCloseKey(key)