Best Python code snippet using keyboard
_darwinkeyboard.py
Source:_darwinkeyboard.py
...166 return (vk, [])167 elif self.layout_specific_keys[vk][1] == character:168 return (vk, ['shift'])169 raise ValueError("Unrecognized character: {}".format(character))170 def vk_to_character(self, vk, modifiers=[]):171 """ Returns a character corresponding to the specified scan code (with given172 modifiers applied) """173 if vk in self.non_layout_keys:174 # Not a character175 return self.non_layout_keys[vk]176 elif vk in self.layout_specific_keys:177 if 'shift' in modifiers:178 return self.layout_specific_keys[vk][1]179 return self.layout_specific_keys[vk][0]180 else:181 # Invalid vk182 raise ValueError("Invalid scan code: {}".format(vk))183class KeyController(object):184 def __init__(self):185 self.key_map = KeyMap()186 self.current_modifiers = {187 "shift": False,188 "caps": False,189 "alt": False,190 "ctrl": False,191 "cmd": False,192 }193 self.media_keys = {194 'KEYTYPE_SOUND_UP': 0,195 'KEYTYPE_SOUND_DOWN': 1,196 'KEYTYPE_BRIGHTNESS_UP': 2,197 'KEYTYPE_BRIGHTNESS_DOWN': 3,198 'KEYTYPE_CAPS_LOCK': 4,199 'KEYTYPE_HELP': 5,200 'POWER_KEY': 6,201 'KEYTYPE_MUTE': 7,202 'UP_ARROW_KEY': 8,203 'DOWN_ARROW_KEY': 9,204 'KEYTYPE_NUM_LOCK': 10,205 'KEYTYPE_CONTRAST_UP': 11,206 'KEYTYPE_CONTRAST_DOWN': 12,207 'KEYTYPE_LAUNCH_PANEL': 13,208 'KEYTYPE_EJECT': 14,209 'KEYTYPE_VIDMIRROR': 15,210 'KEYTYPE_PLAY': 16,211 'KEYTYPE_NEXT': 17,212 'KEYTYPE_PREVIOUS': 18,213 'KEYTYPE_FAST': 19,214 'KEYTYPE_REWIND': 20,215 'KEYTYPE_ILLUMINATION_UP': 21,216 'KEYTYPE_ILLUMINATION_DOWN': 22,217 'KEYTYPE_ILLUMINATION_TOGGLE': 23218 }219 220 def press(self, key_code):221 """ Sends a 'down' event for the specified scan code """222 if key_code >= 128:223 # Media key224 ev = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_(225 14, # type226 (0, 0), # location227 0xa00, # flags228 0, # timestamp229 0, # window230 0, # ctx231 8, # subtype232 ((key_code-128) << 16) | (0xa << 8), # data1233 -1 # data2234 )235 Quartz.CGEventPost(0, ev.CGEvent())236 else:237 # Regular key238 # Apply modifiers if necessary239 event_flags = 0240 if self.current_modifiers["shift"]:241 event_flags += Quartz.kCGEventFlagMaskShift242 if self.current_modifiers["caps"]:243 event_flags += Quartz.kCGEventFlagMaskAlphaShift244 if self.current_modifiers["alt"]:245 event_flags += Quartz.kCGEventFlagMaskAlternate246 if self.current_modifiers["ctrl"]:247 event_flags += Quartz.kCGEventFlagMaskControl248 if self.current_modifiers["cmd"]:249 event_flags += Quartz.kCGEventFlagMaskCommand250 251 # Update modifiers if necessary252 if key_code == 0x37: # cmd253 self.current_modifiers["cmd"] = True254 elif key_code == 0x38 or key_code == 0x3C: # shift or right shift255 self.current_modifiers["shift"] = True256 elif key_code == 0x39: # caps lock257 self.current_modifiers["caps"] = True258 elif key_code == 0x3A: # alt259 self.current_modifiers["alt"] = True260 elif key_code == 0x3B: # ctrl261 self.current_modifiers["ctrl"] = True262 event = Quartz.CGEventCreateKeyboardEvent(None, key_code, True)263 Quartz.CGEventSetFlags(event, event_flags)264 Quartz.CGEventPost(Quartz.kCGHIDEventTap, event)265 time.sleep(0.01)266 def release(self, key_code):267 """ Sends an 'up' event for the specified scan code """268 if key_code >= 128:269 # Media key270 ev = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_(271 14, # type272 (0, 0), # location273 0xb00, # flags274 0, # timestamp275 0, # window276 0, # ctx277 8, # subtype278 ((key_code-128) << 16) | (0xb << 8), # data1279 -1 # data2280 )281 Quartz.CGEventPost(0, ev.CGEvent())282 else:283 # Regular key284 # Update modifiers if necessary285 if key_code == 0x37: # cmd286 self.current_modifiers["cmd"] = False287 elif key_code == 0x38 or key_code == 0x3C: # shift or right shift288 self.current_modifiers["shift"] = False289 elif key_code == 0x39: # caps lock290 self.current_modifiers["caps"] = False291 elif key_code == 0x3A: # alt292 self.current_modifiers["alt"] = False293 elif key_code == 0x3B: # ctrl294 self.current_modifiers["ctrl"] = False295 # Apply modifiers if necessary296 event_flags = 0297 if self.current_modifiers["shift"]:298 event_flags += Quartz.kCGEventFlagMaskShift299 if self.current_modifiers["caps"]:300 event_flags += Quartz.kCGEventFlagMaskAlphaShift301 if self.current_modifiers["alt"]:302 event_flags += Quartz.kCGEventFlagMaskAlternate303 if self.current_modifiers["ctrl"]:304 event_flags += Quartz.kCGEventFlagMaskControl305 if self.current_modifiers["cmd"]:306 event_flags += Quartz.kCGEventFlagMaskCommand307 event = Quartz.CGEventCreateKeyboardEvent(None, key_code, False)308 Quartz.CGEventSetFlags(event, event_flags)309 Quartz.CGEventPost(Quartz.kCGHIDEventTap, event)310 time.sleep(0.01)311 def map_char(self, character):312 if character in self.media_keys:313 return (128+self.media_keys[character],[])314 else:315 return self.key_map.character_to_vk(character)316 def map_scan_code(self, scan_code):317 if scan_code >= 128:318 character = [k for k, v in enumerate(self.media_keys) if v == scan_code-128]319 if len(character):320 return character[0]321 return None322 else:323 return self.key_map.vk_to_character(scan_code)324class KeyEventListener(object):325 def __init__(self, callback, blocking=False):326 self.blocking = blocking327 self.callback = callback328 self.listening = True329 self.tap = None330 def run(self):331 """ Creates a listener and loops while waiting for an event. Intended to run as332 a background thread. """333 self.tap = Quartz.CGEventTapCreate(334 Quartz.kCGSessionEventTap,335 Quartz.kCGHeadInsertEventTap,336 Quartz.kCGEventTapOptionDefault,337 Quartz.CGEventMaskBit(Quartz.kCGEventKeyDown) |...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!