This snippet defines a function mousepos() which gets the mouse position on the screen. The package python-xlib is required.

# (linux only)
"""module mousepos
# uses the package python-xlib
# from

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()))
About the Author
Member Avatar Gribouillis Programming Explorer

Mind explorer.

If someone has a similar snippet for windows, it would be nice to add it to this code snippet :)

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()
    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 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']
>>>, 500)
>>>, 500)
>>> mouse.screen_size()
(1280, 1024)
>>> mouse.position()
(708, 894)

The story goes on: there is now PyUserInput which embeds pymouse and adds keyboard control too :). Install it from pypi.

Sweet. Much nicer than termios solutions.