Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use xdotool from within a python module/script?

Tags:

python

ubuntu

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 these commands straight into the terminal to get the desired effect but I would like to put them inside of a Python script.

like image 426
coffeeNcode Avatar asked Mar 13 '12 10:03

coffeeNcode


3 Answers

import subprocess

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

etc. See the subprocess docs.

like image 137
Fred Foo Avatar answered Nov 14 '22 01:11

Fred Foo


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')
like image 35
John 9631 Avatar answered Nov 14 '22 02:11

John 9631


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

like image 9
Simon Avatar answered Nov 14 '22 01:11

Simon