Skip to content

Instantly share code, notes, and snippets.

@danbradham
Last active November 22, 2022 08:06
Show Gist options
  • Save danbradham/9975959 to your computer and use it in GitHub Desktop.
Save danbradham/9975959 to your computer and use it in GitHub Desktop.
Autodesk Maya hotkeys with Python
from __future__ import print_function
from collections import namedtuple
from maya import cmds
import pymel.core as pmc
from maya.utils import executeDeferred
from functools import wraps
KeySequence = namedtuple('KeySequence', 'ctrl shift alt key full')
def command_exists(name):
'''Check if a runTimeCommand exists'''
return cmds.runTimeCommand(name, query=True, exists=True)
def parse_key_sequence(key_sequence):
'''
Returns a KeySequence object from a string like::
"Ctrl+Alt+O"
"ctrl+shift+m"
"m"
"alt+M"
'''
keys = KeySequence(False, False, False, '', key_sequence)
key_sequence = key_sequence.lower()
for modifier in ['ctrl', 'shift', 'alt']:
group = modifier + '+'
if group in key_sequence:
keys = keys._replace(**{modifier: True})
key_sequence = key_sequence.replace(group, '')
keys = keys._replace(key=key_sequence)
return keys
def defer(fn):
'''Delays execution of the decorated function until Maya is idle.'''
@wraps(fn)
def deferred(*args, **kwargs):
executeDeferred(fn, *args, **kwargs)
return deferred
@defer
def create_hotkey(key_sequence, name, command, category='Custom Scripts', release_name=None, release_command=None):
keys = parse_key_sequence(key_sequence)
params = dict(
keyShortcut=keys.key,
ctrlModifier=keys.ctrl,
altModifier=keys.alt,
shiftModifier=keys.shift,
name=name
)
unbind_params = dict(params)
unbind_params['name']= ''
unbind_params['releaseName'] = ''
if not command_exists(name):
cmds.runTimeCommand(
name,
category=category,
command=command,
commandLanguage='python'
)
cmds.nameCommand(
name,
ann=name,
sourceType='python',
command=name
)
if release_name and release_command:
if not command_exists(release_name):
cmds.runTimeCommand(
release_name,
category=category,
command=release_command,
commandLanguage='python'
)
cmds.nameCommand(
name,
ann=name,
sourceType='python',
command=name
)
params['releaseName'] = release_name
pmc.hotkey(**unbind_params)
pmc.hotkey(**params)
hotline_command = """
from hotline import Hotline
import __main__
if not hasattr(__main__, 'hl'):
__main__.hl = Hotline()
__main__.hl.show()
"""
create_hotkey('H', 'Hotline', hotline_command)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment