pythonrandomnumberskeystrokeletter

Python: Generate random letter then Keystroke said letter


(I am using Python under Mac OS)

Hey Guys,

i am looking for a way to random generate a letter (a-z) and then keystroke it. The way I usually do keystrokes is:

cmd = """ osascript -e 'tell application 'System Events' to keystroke "insert_letter_here"' """

os.system(cmd)

This won't accept random.letter since it would keystroke the exact spelling of random.letter.

Does anyone know a way to first generate a random letter and then keystroke it?

Thanks in advance!


Solution

  • There are many ways to achieve this, but here is one:

    import random, string, keyboard
    
    random_letter = random.choice(string.ascii_letters)
    keyboard.write(random_letter)
    

    The random letter can be both lower and upper case in this example because string.ascii_letters returns:

    'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    

    (you may have to pip install the keyboard library)