# mousepos.py (linux only)
"""module mousepos
"""
# uses the package python-xlib
# from http://snipplr.com/view/19188/mouseposition-on-linux-via-xlib/

from Xlib import display

def mousepos():
    """mousepos() --> (x, y) get the mouse coordinates on the screen (linux, Xlib)."""
    data = display.Display().screen().root.query_pointer()._data
    return data["root_x"], data["root_y"]

if __name__ == "__main__":
    print("The mouse position on the screen is {0}".format(mousepos()))

I found the corresponding functionality for windows (you need the python for windows extensions)

from win32api import GetCursorPos as mousepos
if __name__ == "__main__":
    print("The mouse position on the screen is {0}".format(mousepos()))

This code also works with Python3 ...

# explore module ctypes to get mouse position
# tested with Python 2.5.4 and Python 3.1.1

import ctypes as ct

class GetPoint(ct.Structure):
    _fields_ = [("x", ct.c_ulong), ("y", ct.c_ulong)]

def get_mousepos():
    pt = GetPoint()
    ct.windll.user32.GetCursorPos(ct.byref(pt))
    return int(pt.x), int(pt.y)

print( "Mouse position at start of program:" )
print( "x=%d, y=%d" % get_mousepos() )

As pointed out by woooee, there is a google code project pymouse which purpose is to provide platform-agnostic methods to handle the mouse.

PyMouse moved to http://github.com/pepijndevos/PyMouse. I tested it on a 64 bits linux box. It seems to give a nice control of the mouse. Here is a example session with the release 1.0

>>> import pymouse
>>> dir(pymouse)
['PyMouse', 'PyMouseEvent', 'PyMouseEventMeta', 'PyMouseMeta', 'Thread', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'sys', 'unix']
>>> mouse = pymouse.PyMouse()
>>> mouse.move(100, 200)
>>> mouse.move(100, 200)
>>> mouse.move(300, 100)
>>> dir(mouse)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'click', 'move', 'position', 'press', 'release', 'screen_size']
>>> mouse.click(400, 500)
>>> mouse.click(400, 500)
>>> mouse.screen_size()
(1280, 1024)
>>> mouse.position()
(708, 894)

Edited 6 Years Ago by Gribouillis: n/a

The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.