def test_registry_read_error(self):
import _winreg
class MockWinreg(object):
def OpenKey(self, key, name):
if key != _winreg.HKEY_CLASSES_ROOT:
raise WindowsError(5, "Access is denied")
return _winreg.OpenKey(key, name)
def __getattr__(self, name):
return getattr(_winreg, name)
mimetypes._winreg = MockWinreg()
try:
mimetypes.init()
finally:
mimetypes._winreg = _winreg
python类HKEY_CLASSES_ROOT的实例源码
def test_registry_read_error(self):
import _winreg
class MockWinreg(object):
def OpenKey(self, key, name):
if key != _winreg.HKEY_CLASSES_ROOT:
raise WindowsError(5, "Access is denied")
return _winreg.OpenKey(key, name)
def __getattr__(self, name):
return getattr(_winreg, name)
mimetypes._winreg = MockWinreg()
try:
mimetypes.init()
finally:
mimetypes._winreg = _winreg
def test_registry_read_error(self):
import _winreg
class MockWinreg(object):
def OpenKey(self, key, name):
if key != _winreg.HKEY_CLASSES_ROOT:
raise WindowsError(5, "Access is denied")
return _winreg.OpenKey(key, name)
def __getattr__(self, name):
return getattr(_winreg, name)
mimetypes._winreg = MockWinreg()
try:
mimetypes.init()
finally:
mimetypes._winreg = _winreg
def remove_jupyter_here():
for env in ('qtconsole', 'notebook'):
try:
winreg.DeleteKey(
winreg.HKEY_CLASSES_ROOT,
r'Directory\shell\jupyter_%s_here\Command' %
env)
winreg.DeleteKey(
winreg.HKEY_CLASSES_ROOT,
r'Directory\shell\jupyter_%s_here' %
env)
winreg.DeleteKey(
winreg.HKEY_CLASSES_ROOT,
r'Directory\Background\shell\jupyter_%s_here\Command' %
env)
winreg.DeleteKey(
winreg.HKEY_CLASSES_ROOT,
r'Directory\Background\shell\jupyter_%s_here' %
env)
print("Jupyter %s here context menu entry removed." % env)
except:
# If this fails it is because it was not installed, so nothing to
# worry about.
pass
def get_data(rootkey, key, value):
"""This method acts as a wrapper for the internal __get_data method.
Args:
root_key (str): The root key as abbreviated string.
Valid values: [hklm, hkcr, hkcu, hku, hkpd, hkcc].
key (str): The subkey starting from the root key.
e.g.: SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
value (str): The value to query.
e.g.: DhcpNameServer
Returns:
str. It returns the retrieved data if the value is correct,
or an empty string otherwise.
"""
rks = [rk.split()[0] for rk in RegistryUtils.ROOT_KEYS]
if rootkey == rks[0]:
return RegistryUtils.__get_data(_winreg.HKEY_LOCAL_MACHINE, key, value)
elif rootkey == rks[1]:
return RegistryUtils.__get_data(_winreg.HKEY_CLASSES_ROOT, key, value)
elif rootkey == rks[2]:
return RegistryUtils.__get_data(_winreg.HKEY_CURRENT_USER, key, value)
elif rootkey == rks[3]:
return RegistryUtils.__get_data(_winreg.HKEY_USERS, key, value)
elif rootkey == rks[4]:
return RegistryUtils.__get_data(_winreg.HKEY_PERFORMANCE_DATA, key, value)
elif rootkey == rks[5]:
return RegistryUtils.__get_data(_winreg.HKEY_CURRENT_CONFIG, key, value)
else:
logging.error('Incorrect registry root key value: {0}. Valid values: {1}'.format(rootkey, RegistryUtils.ROOT_KEYS))
return ''
def get_key_values(rootkey, key):
"""This method acts as a wrapper for the internal __get_key_values method.
Args:
root_key (str): The root key as abbreviated string.
Valid values: [hklm, hkcr, hkcu, hku, hkpd, hkcc].
key (str): The subkey starting from the root key.
e.g.: SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
Returns:
list. It returns the retrieved values and subkeys
or an empty list if data could not be retrieved.
"""
rks = [rk.split()[0] for rk in RegistryUtils.ROOT_KEYS]
if rootkey == rks[0]:
return RegistryUtils.__get_key_values(_winreg.HKEY_LOCAL_MACHINE, key)
elif rootkey == rks[1]:
return RegistryUtils.__get_key_values(_winreg.HKEY_CLASSES_ROOT, key)
elif rootkey == rks[2]:
return RegistryUtils.__get_key_values(_winreg.HKEY_CURRENT_USER, key)
elif rootkey == rks[3]:
return RegistryUtils.__get_key_values(_winreg.HKEY_USERS, key)
elif rootkey == rks[4]:
return RegistryUtils.__get_key_values(_winreg.HKEY_PERFORMANCE_DATA, key)
elif rootkey == rks[5]:
return RegistryUtils.__get_key_values(_winreg.HKEY_CURRENT_CONFIG, key)
else:
logging.error('Incorrect registry root key value: {0}. Valid values: {1}'.format(rootkey, RegistryUtils.ROOT_KEYS))
return []
def RegisterPythonServer(filename, progids=None, verbose=0):
if progids:
if isinstance(progids, basestring):
progids = [progids]
# we know the CLSIDs we need, but we might not be an admin user
# and otherwise unable to register them. So as long as the progids
# exist and the DLL points at our version, assume it already is.
why_not = None
for progid in progids:
try:
clsid = pythoncom.MakeIID(progid)
except pythoncom.com_error:
# no progid - not registered.
break
# have a CLSID - open it.
try:
HKCR = _winreg.HKEY_CLASSES_ROOT
hk = _winreg.OpenKey(HKCR, "CLSID\\%s" % clsid)
dll = _winreg.QueryValue(hk, "InprocServer32")
except WindowsError:
# no CLSID or InProcServer32 - not good!
break
ok_files = [os.path.basename(pythoncom.__file__),
'pythoncomloader%d%d.dll' % (sys.version_info[0], sys.version_info[1])]
if os.path.basename(dll) not in ok_files:
why_not = "%r is registered against a different Python version (%s)" % (progid, dll)
break
else:
#print "Skipping registration of '%s' - already registered" % filename
return
# needs registration - see if its likely!
try:
from win32com.shell.shell import IsUserAnAdmin
except ImportError:
print "Can't import win32com.shell - no idea if you are an admin or not?"
is_admin = False
else:
try:
is_admin = IsUserAnAdmin()
except pythoncom.com_error:
# old, less-secure OS - assume *is* admin.
is_admin = True
if not is_admin:
msg = "%r isn't registered, but I'm not an administrator who can register it." % progids[0]
if why_not:
msg += "\n(registration check failed as %s)" % why_not
# throw a normal "class not registered" exception - we don't report
# them the same way as "real" errors.
raise pythoncom.com_error(winerror.CO_E_CLASSSTRING, msg, None, -1)
# so theoretically we are able to register it.
cmd = '%s "%s" --unattended > nul 2>&1' % (win32api.GetModuleFileName(0), filename)
if verbose:
print "Registering engine", filename
# print cmd
rc = os.system(cmd)
if rc:
print "Registration command was:"
print cmd
raise RuntimeError("Registration of engine '%s' failed" % filename)
def RegisterPythonServer(filename, progids=None, verbose=0):
if progids:
if isinstance(progids, basestring):
progids = [progids]
# we know the CLSIDs we need, but we might not be an admin user
# and otherwise unable to register them. So as long as the progids
# exist and the DLL points at our version, assume it already is.
why_not = None
for progid in progids:
try:
clsid = pythoncom.MakeIID(progid)
except pythoncom.com_error:
# no progid - not registered.
break
# have a CLSID - open it.
try:
HKCR = _winreg.HKEY_CLASSES_ROOT
hk = _winreg.OpenKey(HKCR, "CLSID\\%s" % clsid)
dll = _winreg.QueryValue(hk, "InprocServer32")
except WindowsError:
# no CLSID or InProcServer32 - not good!
break
ok_files = [os.path.basename(pythoncom.__file__),
'pythoncomloader%d%d.dll' % (sys.version_info[0], sys.version_info[1])]
if os.path.basename(dll) not in ok_files:
why_not = "%r is registered against a different Python version (%s)" % (progid, dll)
break
else:
#print "Skipping registration of '%s' - already registered" % filename
return
# needs registration - see if its likely!
try:
from win32com.shell.shell import IsUserAnAdmin
except ImportError:
print "Can't import win32com.shell - no idea if you are an admin or not?"
is_admin = False
else:
try:
is_admin = IsUserAnAdmin()
except pythoncom.com_error:
# old, less-secure OS - assume *is* admin.
is_admin = True
if not is_admin:
msg = "%r isn't registered, but I'm not an administrator who can register it." % progids[0]
if why_not:
msg += "\n(registration check failed as %s)" % why_not
# throw a normal "class not registered" exception - we don't report
# them the same way as "real" errors.
raise pythoncom.com_error(winerror.CO_E_CLASSSTRING, msg, None, -1)
# so theoretically we are able to register it.
cmd = '%s "%s" --unattended > nul 2>&1' % (win32api.GetModuleFileName(0), filename)
if verbose:
print "Registering engine", filename
# print cmd
rc = os.system(cmd)
if rc:
print "Registration command was:"
print cmd
raise RuntimeError("Registration of engine '%s' failed" % filename)
def RegisterPythonServer(filename, progids=None, verbose=0):
if progids:
if isinstance(progids, basestring):
progids = [progids]
# we know the CLSIDs we need, but we might not be an admin user
# and otherwise unable to register them. So as long as the progids
# exist and the DLL points at our version, assume it already is.
why_not = None
for progid in progids:
try:
clsid = pythoncom.MakeIID(progid)
except pythoncom.com_error:
# no progid - not registered.
break
# have a CLSID - open it.
try:
HKCR = _winreg.HKEY_CLASSES_ROOT
hk = _winreg.OpenKey(HKCR, "CLSID\\%s" % clsid)
dll = _winreg.QueryValue(hk, "InprocServer32")
except WindowsError:
# no CLSID or InProcServer32 - not good!
break
ok_files = [os.path.basename(pythoncom.__file__),
'pythoncomloader%d%d.dll' % (sys.version_info[0], sys.version_info[1])]
if os.path.basename(dll) not in ok_files:
why_not = "%r is registered against a different Python version (%s)" % (progid, dll)
break
else:
#print "Skipping registration of '%s' - already registered" % filename
return
# needs registration - see if its likely!
try:
from win32com.shell.shell import IsUserAnAdmin
except ImportError:
print "Can't import win32com.shell - no idea if you are an admin or not?"
is_admin = False
else:
try:
is_admin = IsUserAnAdmin()
except pythoncom.com_error:
# old, less-secure OS - assume *is* admin.
is_admin = True
if not is_admin:
msg = "%r isn't registered, but I'm not an administrator who can register it." % progids[0]
if why_not:
msg += "\n(registration check failed as %s)" % why_not
# throw a normal "class not registered" exception - we don't report
# them the same way as "real" errors.
raise pythoncom.com_error(winerror.CO_E_CLASSSTRING, msg, None, -1)
# so theoretically we are able to register it.
cmd = '%s "%s" --unattended > nul 2>&1' % (win32api.GetModuleFileName(0), filename)
if verbose:
print "Registering engine", filename
# print cmd
rc = os.system(cmd)
if rc:
print "Registration command was:"
print cmd
raise RuntimeError("Registration of engine '%s' failed" % filename)