MSS API

Classes

macOS

mss.darwin.CFUNCTIONS

GNU/Linux

mss.linux.CFUNCTIONS
mss.linux.ERROR
Type:types.SimpleNamspacedict

The details attribute contains the latest Xlib or XRANDR function. It is a dict.

New in version 5.0.0.

mss.linux.PLAINMASK
mss.linux.ZPIXMAP
class mss.linux.MSS
__init__([display=None])
Parameters:display (str or None) – The display to use.

GNU/Linux initializations.

get_error_details()
Return type:Optional[dict[str, Any]]

Get more information about the latest X server error. To use in such scenario:

with mss.mss() as sct:
    # Take a screenshot of a region out of monitor bounds
    rect = {"left": -30, "top": 0, "width": 100, "height": 100}

    try:
        sct.grab(rect)
    except ScreenShotError:
        details = sct.get_error_details()
        """
        >>> import pprint
        >>> pprint.pprint(details)
        {'xerror': 'BadFont (invalid Font parameter)',
         'xerror_details': {'error_code': 7,
                            'minor_code': 0,
                            'request_code': 0,
                            'serial': 422,
                            'type': 0}}
        """

New in version 4.0.0.

grab(monitor)
Return type:ScreenShot
Raises:ScreenShotError – When color depth is not 32 (rare).

See grab() for details.

mss.linux.error_handler(display, event)
Parameters:
  • display (ctypes.POINTER(Display)) – The display impacted by the error.
  • event (ctypes.POINTER(Event)) – XError details.
Return int:

Always 0.

Error handler passed to X11.XSetErrorHandler() to catch any error that can happen when calling a X11 function. This will prevent Python interpreter crashes.

When such an error happen, a ScreenShotError exception is raised and all XError information are added to the details attribute.

New in version 3.3.0.

Windows

mss.windows.CAPTUREBLT
mss.windows.CFUNCTIONS
mss.windows.DIB_RGB_COLORS
mss.windows.SRCCOPY

Methods

class mss.base.MSSBase

The parent’s class for every OS implementation.

close()

Clean-up method. Does nothing by default.

New in version 4.0.0.

grab(region)
Parameters:monitor (dict) – region’s coordinates.
Return type:ScreenShot

Retrieve screen pixels for a given region. Subclasses need to implement this.

Note

monitor can be a tuple like PIL.Image.grab() accepts, it will be converted to the appropriate dict.

save([mon=1][, output='mon-{mon}.png'][, callback=None])
Parameters:
  • mon (int) – the monitor’s number.
  • output (str) – the output’s file name.
  • callback (callable or None) – callback called before saving the screen shot to a file. Takes the output argument as parameter.
Return type:

iterable

Returns:

Created file(s).

Grab a screen shot and save it to a file. The output parameter can take several keywords to customize the filename:

  • {mon}: the monitor number
  • {top}: the screen shot y-coordinate of the upper-left corner
  • {left}: the screen shot x-coordinate of the upper-left corner
  • {width}: the screen shot’s width
  • {height}: the screen shot’s height
  • {date}: the current date using the default formatter

As it is using the format() function, you can specify formatting options like {date:%Y-%m-%s}.

Warning

On Windows, the default date format may result with a filename containing ‘:’ which is not allowed:

IOerror: [Errno 22] invalid mode ('wb') or filename: 'sct_1-2019-01-01 21:20:43.114194.png'

To fix this, you must provide a custom date formatting.

shot()
Return str:The created file.

Helper to save the screen shot of the first monitor, by default. You can pass the same arguments as for save().

New in version 3.0.0.

class mss.base.ScreenShot

Screen shot object.

Note

A better name would have been Image, but to prevent collisions with PIL.Image, it has been decided to use ScreenShot.

classmethod from_size(cls, data, width, height)
Parameters:
  • data (bytearray) – raw BGRA pixels retrieved by ctypes OS independent implementations.
  • width (int) – the monitor’s width.
  • height (int) – the monitor’s height.
Return type:

ScreenShot

Instantiate a new class given only screen shot’s data and size.

pixel(coord_x, coord_y)
Parameters:
  • coord_x (int) – The x coordinate.
  • coord_y (int) – The y coordinate.
Return type:

tuple(int, int, int)

Get the pixel value at the given position.

New in version 3.0.0.

mss.tools.to_png(data, size, level=6, output=None)
Parameters:
  • data (bytes) – RGBRGB…RGB data.
  • size (tuple) – The (width, height) pair.
  • level (int) – PNG compression level.
  • output (str) – output’s file name.
Raises:

Dump data to the image file. Pure Python PNG implementation. If output is None, create no file but return the whole PNG data.

New in version 3.0.0.

Changed in version 3.2.0: The level keyword argument to control the PNG compression level.

Properties

class mss.base.MSSBase
monitors

Positions of all monitors. If the monitor has rotation, you have to deal with it inside this method.

This method has to fill self._monitors with all information and use it as a cache:

  • self._monitors[0] is a dict of all monitors together
  • self._monitors[N] is a dict of the monitor N (with N > 0)

Each monitor is a dict with:

  • left: the x-coordinate of the upper-left corner
  • top: the y-coordinate of the upper-left corner
  • width: the width
  • height: the height

Subclasses need to implement this.

Return type:list[dict[str, int]]
class mss.base.ScreenShot
__array_interface__

Numpy array interface support. It uses raw data in BGRA form.

Return type:dict[str, Any]
bgra

BGRA values from the BGRA raw pixels.

Return type:bytes

New in version 3.2.0.

height

The screen shot’s height.

Return type:int
left

The screen shot’s left coordinate.

Return type:int
pixels

List of RGB tuples.

Return type:list[tuple(int, int, int)]
pos

The screen shot’s coordinates.

Return type:collections.namedtuple()
rgb

Computed RGB values from the BGRA raw pixels.

Return type:bytes

New in version 3.0.0.

size

The screen shot’s size.

Return type:collections.namedtuple()
top

The screen shot’s top coordinate.

Return type:int
width

The screen shot’s width.

Return type:int

Exception

exception mss.exception.ScreenShotError

Base class for MSS exceptions.

details

On GNU/Linux, and if the error comes from the XServer, it contains XError details. This is an empty dict by default.

For XErrors, you can find information on Using the Default Error Handlers.

Return type:dict[str, Any]

New in version 3.3.0.

Factory

mss.factory.mss()

Factory function to instance the appropriate MSS class.