Get key name in python

Asked by Dillon on 2018-07-16

Is there a function to get the name of a key as a string in Python?
Example str(Key.WIN) -> "Windows"

Question information

Language:
English Edit question
Status:
Solved
For:
Sikuli Edit question
Assignee:
No assignee Edit question
Solved by:
Dillon
Solved:
2018-07-16
Last query:
2018-07-16
Last reply:
2018-07-16
Alex (carroll-alex-d) said : #1

Can you provide more information? The following commands work fine in Sikuli:

CTRL+A to select all
type('a', Key.CTRL)

type(Key.TAB, Key.ALT)

I'm not really sure what you are asking but I would be happy to help.

Dillon (dillonm197) said : #2

Post updated.

Alex (carroll-alex-d) said : #3

I'm not aware of the existence of this functionality. The [Key Constants](http://sikulix-2014.readthedocs.io/en/latest/keys.html) help page lists all of the available special keys. It would be trivial to make a function that did this:

def print_special_key_string(key):
    """
    Given a special key constant return a string.
    :param key:
    :return:
    """
    if 'Key.' in key:
        key = key.replace('Key.', '') # Strip the 'Key.' text if it exists.

    key_dict = {
        u'\r': 'Enter',
        u'': 'Window',
        u'': 'Escape',
        u'': 'ALT'
    }

    if key in key_dict:
        return key_dict[key]
    else:
        raise ValueError('Unable to locate %s in the Special Key dictionary.' % key)

print(print_special_key_string(Key.WIN))

I couldn't paste the full list in but you get the idea. Make sure you set the encoding at the top of your file:

# -*- coding: utf-8 -*-

Dillon (dillonm197) said : #4

Works splendidly! Thank you very much.