Using Python:
EXT, EXT_TYPE = ".xyz", "XYZ file"
EXE_PATH = r"path\to\my\exe"
# %L is the long (full path) version of path
extCmd = '"%s" "%%L" %%*' % EXE_PATH
# Using assoc and ftype easier than editing registry!
assert os.system('assoc %s=%s' % (EXT, EXT_TYPE))==0
assert os.system('ftype %s=%s' % (EXT_TYPE, extCmd))==0
Associating an icon with the extension type:
import _winreg
try:
ext = _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, EXT_TYPE)
_winreg.SetValue(ext, "DefaultIcon", _winreg.REG_SZ, ICON_PATH)
_winreg.CloseKey(ext)
except WindowsError:
print "Error associating icon"
Register the extension as an executable type (i.e. PATHEXT):
try:
key = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
reg = _winreg.ConnectRegistry( None, _winreg.HKEY_LOCAL_MACHINE )
# get current value
ext = _winreg.OpenKey(reg, key)
pathext = _winreg.QueryValueEx(ext, 'PATHEXT')[0]
if not EXT in pathext:
_winreg.CloseKey(ext)
# modify the current value
ext = _winreg.OpenKey(reg, key, 0, _winreg.KEY_ALL_ACCESS)
pathext += ';' + EXT
_winreg.SetValueEx(ext, 'PATHEXT', 0, _winreg.REG_SZ, pathext)
_winreg.CloseKey(ext)
_winreg.CloseKey(reg)
except WindowsError:
print "Error adding to PATHEXT"
Additionally, to get PATHEXT recognised without logging in again you can update the environment: (thanks to Enthought for this)
def refreshEnvironment():
HWND_BROADCAST = 0xFFFF
WM_SETTINGCHANGE = 0x001A
SMTO_ABORTIFHUNG = 0x0002
sParam = "Environment"
import win32gui
res1, res2 = win32gui.SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, sParam, SMTO_ABORTIFHUNG, 100)