Python 02: fake key or mouse input

RasPython

If you need your python program to emulate a mouse movement/click or a key press here is what you need to do.

There is a terminal command that does exactly what we are trying to accomplish here and its name is xte.
The python way to use xte is to create a child terminal process to execute it and then create a pipe to communicate with it to send our emulated input.

In order to make it easier to reuse the code, I decided to make a function:

from subprocess import Popen, PIPE

def keypress(sequence):
    #creates the xte child process and the pipe
    p = Popen(['xte'], stdin=PIPE)
    #send the command to xte
    p.communicate(input=sequence)

Now, whenever a key press, mouse movement/click is needed, you just need to call keypress() with one of the following commands.

Commands:

key k – Press and release key k
keydown k – Press key k down
keyup k – Release key k
str string – Do a bunch of key X events for each char in string
mouseclick i – Click mouse button i
mousemove x y – Move mouse to screen position x, y
mousermove x y – Move mouse relative from current location by x, y
mousedown i – Press mouse button i down
mouseup i – Release mouse button i
sleep x – Sleep x seconds
usleep x – Sleep x microseconds

Some keys:

  • Home
  • Left
  • Up
  • Right
  • Down
  • Page_Up
  • Page_Down
  • End
  • Return
  • BackSpace
  • Tab
  • Escape
  • Delete
  • Shift_L
  • Shift_R
  • Control_L
  • Control_R
  • Meta_L
  • Meta_R
  • Alt_L
  • Alt_R

Here are some examples:

keypress("mousemove 50 50")
keypress("mouseclick 1 ")
keypress("keydown Shift_L ")

For more help with xte:

$ man xte

 

Advertisements
This entry was posted in Python, Raspberry Pi and tagged , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s