Archive

Posts Tagged ‘keyboard’

Type text to an application from a script

December 28, 2016 1 comment

Problem
Today I saw a nice motivational video: Girl does push ups for 100 days time lapse. Great, let’s do the same! I sit in front of my computer several hours a day, so some pushups won’t hurt :) But how to track the days?

I use Trello for some TODO lists, and it allows you to create a checklist. When you type a text and press Enter, a new checklist item is created. But typing “Day 1<Enter>”, “Day 2<Enter>”, … “Day 100<Enter>” is too much, I would die of boredom by the end… How to automate the input?

Solution
Under Linux there is a command called “xdotool” that (among others) lets you programmatically simulate keyboard input. “xdotool key D” will simulate pressing “D”, “xdotool key KP_Enter” is equivalent to pressing the Enter, etc.

Here is the script:

#!/usr/bin/env python3
# coding: utf-8

import os
from time import sleep

PRE_WAIT = 3

REPEAT = 100
WAIT = 0.3

def my_type(text):
    for c in text:
        if c == " ":
            key = "KP_Space"
        elif c == "\n":
            key = "KP_Enter"
        else:
            key = c
        #
        cmd = "xdotool key {}".format(key)
        os.system(cmd)

def main():
    print("You have {} seconds to switch to the application...".format(PRE_WAIT))
    sleep(PRE_WAIT)
    #
    for i in range(1, REPEAT+1):
        text = "Day {}\n".format(i)
        my_type(text)
        print("#", text)
        sleep(WAIT)

##############################################################################

if __name__ == "__main__":
    main()

Create a checklist in Trello, start adding a new item, launch this script and switch back to Trello. The script will automatically create the items for the days.

screenshot

screenshot

In the screenshot the dates were added manually. As you can see, I could do 20 pushups the very first day. Not bad :)

Update (20170302)
If you want to figure out the key code of a key, then start “xev -event keyboard” and press the given key. For instance, if you want xdotool to press “á” for you, the command above will tell you that the key code of “á” is “aacute“, thus the command to generate “á” is “xdotool key aacute“.

To avoid the special key codes, here is another idea: copy the text to the clipboard (see the command xsel for instance), then paste it with xdotool key "shift+Insert".

Advertisements
Categories: python Tags: , , , ,