Skip to content

Instantly share code, notes, and snippets.

@vidartf
Last active July 28, 2017 09:27
Show Gist options
  • Save vidartf/f5e4429d8078878405084a9a699d4d8b to your computer and use it in GitHub Desktop.
Save vidartf/f5e4429d8078878405084a9a699d4d8b to your computer and use it in GitHub Desktop.
Released under CC0 1.0
import os
def register_file_ext(filetypes, docformat_name, command, icon_path):
"""
Parameters:
-----------
filetypes: sequence of strings
Sequence of string of file extensions with a leading dot (e.g. '.txt')
docformat_name: string
Typically of the format ApplicationName.Document, but other examples
include ..., ... and ...
command: string
The command to execute when a file with one of the given extensions
is executed. You typically want your command to end with '"%1" %*' to
ensure it gets all the passed command line arguments.
icon_path:
Path to an .ico file to use for files associated with your command.
"""
# Setup default icon
cmd = r'1>nul 2>nul REG ADD "HKCR\%s\DefaultIcon" ' % docformat_name
cmd += '/t REG_SZ /f /d "{0}"'.format(
os.path.abspath(icon_path))
# Try to register for all users (requires admin)
r = subprocess.call(cmd, shell=True)
cmds = []
if r == 0: # Everything OK, we're admin. Use ASSOC and FTYPE
for ft in filetypes:
# Call ASSOC .ext=Document.Format
cmds.append(r'1>nul 2>nul ASSOC %s=%s' % (ft, docformat_name))
# Call FTYPE Document.Format=command
cmds.append(r'1>nul 2>nul FTYPE ' +
r'{0}="{1}" "'.format(docformat_name, command))
else:
# Not admin. We have to add everything to HKCU manually
# Add icon:
cmd = (r'1>nul 2>nul REG ADD ' +
r'"HKCU\Software\Classes\%s\DefaultIcon"' % docformat_name) +
r' /t REG_SZ /f /d "'
cmd += os.path.abspath(icon_path)
cmds.append(cmd)
for ft in filetypes:
# ASSOC
cmds.append(
(r'1>nul 2>nul REG ADD "HKCU\Software\Classes\%s" ' % ft) +
(r'/v "" /t REG_SZ /d "%s" /f' % docformat_name))
# FTYPE
cmds.append(
r'1>nul 2>nul REG ADD ' +
(r'"HKCU\Software\Classes\%s\shell\open\command"' %
docformat_name) +
r' /v "" /t REG_EXPAND_SZ /d ' +
(r'"{0}" %*" /f'.format(command))
for cmd in cmds:
r = subprocess.call(cmd, shell=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment