Skip to content Skip to sidebar Skip to footer

How Can I Use Xdotool From Within A Python Module/script?

For example, if I wanted to use something like: xdotool mousemove 945 132 xdotool click 1 In order to move the mouse to a certain location and click. In ubuntu I can just type the

Solution 1:

import subprocess

subprocess.call(["xdotool", "mousemove", "945", "132"])

etc. See the subprocess docs.


Solution 2:

As of 2015 you can also use this python package: https://github.com/rshk/python-libxdo


Solution 3:

I had been using xdotool with sh and os.system for a while but decided to update everything to use subprocess. Doing that I encountered a few minor glitches and in googling discovered the libxdo python module suggested by Simon. There was a small issue with Python3 - it uses bytestrings - but the conversion was simple and it runs more smoothly and reliably that the old two step process.

Here's a little code that may help (obviously the hash bang would need to match your python path). The two functions include the conversion to bytestrings (ascii) for Python 3 so .encode() could be left off for Python 2.

#!/home/john/anaconda3/bin/python3.6
import sys
from xdo import Xdo
from time import sleep

def sendkeys(*keys):
    for k in keys: xdo.send_keysequence_window(0, k.encode())

def type(text):
    xdo.enter_text_window(0, text.encode())

sleep(0.5)
xdo = Xdo()

# this updates a row in a spreadsheet with copies from prior row
# first check that this is the intended spreadsheet
if 'Trades' in xdo.get_window_name(xdo.get_active_window()).decode():
    with open('my_data_file_name', 'r') as f:
        trade = (f.readlines()[-int(sys.argv[1])])[:-1]
        t = [s if s else '0' for s in trade.split('\t')]
        type('\t'.join(t[:7]))
        sendkeys('Tab', 'Up', 'ctrl+c', 'Down', 'ctrl+v', 'Right')
        type(' ' + t[-3])
        sendkeys('Tab')
        type(t[-2])
        sendkeys('Tab')
        type(t[-1])
        sendkeys('Tab', 'Up', 'ctrl+c', 'Down', 'ctrl+v', 'Right')
        type('333')
        sendkeys('Tab')

Post a Comment for "How Can I Use Xdotool From Within A Python Module/script?"