def _create_win(self):
try:
key = _winreg.OpenKey(
_winreg.HKEY_LOCAL_MACHINE,
r'Software\Microsoft\Windows NT\CurrentVersion\Fonts')
except EnvironmentError:
try:
key = _winreg.OpenKey(
_winreg.HKEY_LOCAL_MACHINE,
r'Software\Microsoft\Windows\CurrentVersion\Fonts')
except EnvironmentError:
raise FontNotFound('Can\'t open Windows font registry key')
try:
path = self._lookup_win(key, self.font_name, STYLES['NORMAL'], True)
self.fonts['NORMAL'] = ImageFont.truetype(path, self.font_size)
for style in ('ITALIC', 'BOLD', 'BOLDITALIC'):
path = self._lookup_win(key, self.font_name, STYLES[style])
if path:
self.fonts[style] = ImageFont.truetype(path, self.font_size)
else:
if style == 'BOLDITALIC':
self.fonts[style] = self.fonts['BOLD']
else:
self.fonts[style] = self.fonts['NORMAL']
finally:
_winreg.CloseKey(key)
python类CloseKey()的实例源码
def checkstartup():
# check if it is linux
if os_type == "Linux" or os_type == "FreeBSD" or os_type == 'OpenBSD':
# check if the startup exists
if os.path.exists(home_address + "/.config/autostart/persepolis.desktop"):
return True
else:
return False
# check if it is mac
elif os_type == "Darwin":
# OS X
if os.path.exists(home_address + "/Library/LaunchAgents/com.persepolisdm.plist"):
return True
else:
return False
# check if it is Windows
elif os_type == "Windows":
# try to open startup key and check persepolis value
try:
aKey = winreg.OpenKey(
winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, winreg.KEY_ALL_ACCESS)
startupvalue = winreg.QueryValueEx(aKey, 'persepolis')
startup = True
except WindowsError:
startup = False
# Close the connection
winreg.CloseKey(aKey)
# if the startup enabled or disabled
if startup:
return True
if not startup:
return False
# add startup file
def removestartup():
# check if it is linux
if os_type == 'Linux' or os_type == 'FreeBSD' or os_type == 'OpenBSD':
# remove it
os.remove(home_address + "/.config/autostart/persepolis.desktop")
# check if it is mac OS
elif os_type == "Darwin":
# OS X
if checkstartup():
os.system('launchctl unload ' + home_address +
"/Library/LaunchAgents/com.persepolisdm.plist")
os.remove(home_address +
"/Library/LaunchAgents/com.persepolisdm.plist")
# check if it is Windows
elif os_type == 'Windows':
if checkstartup():
# Connect to the startup path in Registry
key = winreg.OpenKey(
winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, winreg.KEY_ALL_ACCESS)
# remove persepolis from startup
winreg.DeleteValue(key, 'persepolis')
# Close connection
winreg.CloseKey(key)
def _autodetect_official_installreg(self):
try:
key = winreg.OpenKey(
winreg.HKEY_LOCAL_MACHINE,
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\PUTTY_is1",
access=winreg.KEY_READ | winreg.KEY_WOW64_32KEY)
value = winreg.QueryValueEx(key, "InstallLocation")[0]
winreg.CloseKey(key)
exe_file = os.path.join(value, self.EXE_NAME_OFFICIAL)
if os.path.exists(exe_file):
return exe_file
except:
pass
return None
def _autodetect_official_installreg(self):
try:
key = winreg.OpenKey(
winreg.HKEY_LOCAL_MACHINE,
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\FileZilla Client",
access=winreg.KEY_READ | winreg.KEY_WOW64_32KEY)
value = winreg.QueryValueEx(key, "InstallLocation")[0]
winreg.CloseKey(key)
exe_file = os.path.join(value, self.EXE_NAME_OFFICIAL)
if os.path.exists(exe_file):
return exe_file
except:
pass
return None
def _autodetect_official_installreg(self):
try:
key = winreg.OpenKey(
winreg.HKEY_LOCAL_MACHINE,
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\winscp3_is1",
access=winreg.KEY_READ | winreg.KEY_WOW64_32KEY)
value = winreg.QueryValueEx(key, "InstallLocation")[0]
winreg.CloseKey(key)
exe_file = os.path.join(value, self.EXE_NAME_OFFICIAL)
if os.path.exists(exe_file):
return exe_file
except:
pass
return None
def add(name, application):
"""add a new autostart entry"""
key = get_runonce()
try:
winreg.SetValueEx(key, name, 0, winreg.REG_SZ, application)
except WindowsError as e:
print(e)
winreg.CloseKey(key)
def exists(name):
"""check if an autostart entry exists"""
key = get_runonce()
exists = True
try:
winreg.QueryValueEx(key, name)
except WindowsError:
exists = False
winreg.CloseKey(key)
return exists
def remove(name):
"""delete an autostart entry"""
if exists("BingNiceWallpapers"):
key = get_runonce()
winreg.DeleteValue(key, name)
winreg.CloseKey(key)
def remove_from_system_path(pathname, allusers=True, path_env_var='PATH'):
"""Removes all entries from the path which match the value in 'pathname'
You must call broadcast_environment_settings_change() after you are finished
manipulating the environment with this and other functions.
For example,
# Remove Anaconda from PATH
remove_from_system_path(r'C:\Anaconda')
broadcast_environment_settings_change()
"""
pathname = path.normcase(path.normpath(pathname))
envkeys = [(reg.HKEY_CURRENT_USER, r'Environment')]
if allusers:
envkeys.append((reg.HKEY_LOCAL_MACHINE,
r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'))
for root, keyname in envkeys:
key = reg.OpenKey(root, keyname, 0,
reg.KEY_QUERY_VALUE|reg.KEY_SET_VALUE)
reg_value = None
try:
reg_value = reg.QueryValueEx(key, path_env_var)
except WindowsError:
# This will happen if we're a non-admin install and the user has
# no PATH variable.
reg.CloseKey(key)
continue
try:
any_change = False
results = []
for v in reg_value[0].split(os.pathsep):
vexp = sz_expand(v, reg_value[1])
# Check if the expanded path matches the
# requested path in a normalized way
if path.normcase(path.normpath(vexp)) == pathname:
any_change = True
else:
# Append the original unexpanded version to the results
results.append(v)
modified_path = os.pathsep.join(results)
if any_change:
reg.SetValueEx(key, path_env_var, 0, reg_value[1], modified_path)
except:
# If there's an error (e.g. when there is no PATH for the current
# user), continue on to try the next root/keyname pair
reg.CloseKey(key)
def _detect_distro_official(self, given_enabled, given_label, given_path):
dist_props = {
'enabled': given_enabled,
'label': given_label,
'exe_file': None,
'cmd_args': ['-load', '%1'],
'sessions': []}
# label
if not dist_props['label']:
dist_props['label'] = "PuTTY"
# enabled? don't go further if not
if dist_props['enabled'] is None:
dist_props['enabled'] = True
if not dist_props['enabled']:
return dist_props
# find executable
exe_file = None
if given_path:
exe_file = os.path.normpath(os.path.join(given_path, self.EXE_NAME_OFFICIAL))
if not os.path.exists(exe_file):
exe_file = None
if not exe_file:
exe_file = self._autodetect_official_installreg()
if not exe_file:
exe_file = self._autodetect_startmenu(self.EXE_NAME_OFFICIAL, "PuTTY.lnk")
if not exe_file:
exe_file = self._autodetect_official_progfiles()
if not exe_file:
exe_file = self._autodetect_path(self.EXE_NAME_OFFICIAL)
#if not exe_file:
# exe_file = self._autodetect_startmenu(self.EXE_NAME_OFFICIAL, "*putty*.lnk")
if not exe_file:
return None
dist_props['exe_file'] = exe_file
# list configured sessions
try:
hkey = winreg.OpenKey(
winreg.HKEY_CURRENT_USER,
'Software\\SimonTatham\\PuTTY\\Sessions')
index = 0
while True:
try:
dist_props['sessions'].append(urllib.parse.unquote(
winreg.EnumKey(hkey, index), encoding='mbcs'))
index += 1
except OSError:
break
winreg.CloseKey(hkey)
except OSError:
pass
return dist_props
def _list_item_info(self, clsid, reg_clsid):
def _getregstr(hkey, sub_path, value_name):
try:
if sub_path is not None:
hkey_sub = winreg.OpenKey(hkey, sub_path)
else:
hkey_sub = hkey
(val, typ) = winreg.QueryValueEx(hkey_sub, value_name)
if sub_path is not None:
winreg.CloseKey(hkey_sub)
if isinstance(val, str) and len(val) > 0:
return val
except OSError:
pass
return None
cpitem = {
'clsid': clsid,
'canonical_name': _getregstr(reg_clsid, None, "System.ApplicationName"),
'open_command': _getregstr(reg_clsid, "Shell\\Open\\Command", None),
'label': None,
'short_desc': None,
'icon_location': _getregstr(reg_clsid, "DefaultIcon", None),
'icon_handle': None}
# skip item if it doesn't have a canonical name or a command to execute
if not cpitem['canonical_name'] and not cpitem['open_command']:
return None
# label
location = _getregstr(reg_clsid, None, "LocalizedString")
if location is not None:
cpitem['label'] = kpu.shell_string_resource(location)
if cpitem['label'] is None:
cpitem['label'] = _getregstr(reg_clsid, None, None)
# skip item if it doesn't have a label
if not cpitem['label']:
return None
# short_desc
location = _getregstr(reg_clsid, None, "InfoTip")
if location is not None:
cpitem['short_desc'] = kpu.shell_string_resource(location)
if cpitem['short_desc'] is None:
cpitem['short_desc'] = ""
# icon
if cpitem['icon_location'] is not None:
if cpitem['icon_location'][0] != '@':
cpitem['icon_location'] = '@' + cpitem['icon_location']
cpitem['icon_handle'] = self.load_icon(cpitem['icon_location'])
return cpitem