### Check pyscreenshot Backend Versions Source: https://github.com/ponty/pyscreenshot/blob/master/README.md This command-line example shows how to check the versions of installed backends compatible with pyscreenshot. It is useful for debugging and ensuring compatibility. ```console $ python3 -m pyscreenshot.check.versions python 3.10.6 pyscreenshot 3.1 pil 9.0.1 mss 7.0.1 scrot 1.7 grim ?.? maim 5.6.3 imagemagick 6.9.11 pyqt5 5.15.6 pyside2 5.15.2 wx 4.0.7 pygdk3 3.42.1 mac_screencapture mac_quartz freedesktop_dbus ?.? gnome_dbus ?.? gnome-screenshot 41.0 ``` -------------------------------- ### Installation Source: https://context7.com/ponty/pyscreenshot/llms.txt Install pyscreenshot along with Pillow for image handling. ```APIDOC ## Installation Install pyscreenshot with Pillow using pip. ```bash pip install Pillow pyscreenshot ``` ``` -------------------------------- ### Create Screenshot with Virtual Display and xmessage Source: https://github.com/ponty/pyscreenshot/blob/master/README.md This example demonstrates how to create a screenshot of an application running in a virtual display using Xvfb and xmessage. It requires the easyprocess and pyvirtualdisplay libraries. ```python from time import sleep from easyprocess import EasyProcess from pyvirtualdisplay import Display import pyscreenshot as ImageGrab with Display(size=(100, 60)) as disp: # start Xvfb display # display is available with EasyProcess(["xmessage", "hello"]): # start xmessage sleep(1) # wait for displaying window img = ImageGrab.grab() img.save("xmessage.png") ``` -------------------------------- ### Speedtest for pyscreenshot Backends (with subprocess) Source: https://github.com/ponty/pyscreenshot/blob/master/README.md This command-line example runs a speed test on various pyscreenshot backends when they are started in a subprocess. This is the default and safest setting. ```console $ python3 -m pyscreenshot.check.speedtest n=10 ------------------------------------------------------ default 1 sec ( 100 ms per call) pil 1.7 sec ( 167 ms per call) mss 2 sec ( 197 ms per call) scrot 1 sec ( 100 ms per call) grim maim 1.4 sec ( 135 ms per call) imagemagick 2.2 sec ( 221 ms per call) pyqt5 4 sec ( 403 ms per call) pyside2 3.9 sec ( 394 ms per call) wx 2.9 sec ( 293 ms per call) pygdk3 2.2 sec ( 218 ms per call) mac_screencapture mac_quartz gnome_dbus gnome-screenshot 4 sec ( 401 ms per call) ``` -------------------------------- ### Install pyscreenshot Source: https://github.com/ponty/pyscreenshot/blob/master/README.md Use pip to install the library along with the recommended Pillow dependency. ```console $ python3 -m pip install Pillow pyscreenshot ``` -------------------------------- ### Speedtest for pyscreenshot Backends (without subprocess) Source: https://github.com/ponty/pyscreenshot/blob/master/README.md This command-line example runs a speed test on various pyscreenshot backends when they are NOT started in a subprocess. This setting is generally faster but may be less stable. ```console $ python3 -m pyscreenshot.check.speedtest --childprocess 0 n=10 ------------------------------------------------------ default 0.13 sec ( 12 ms per call) pil 0.12 sec ( 11 ms per call) mss 0.2 sec ( 19 ms per call) scrot 1 sec ( 99 ms per call) grim maim 1.3 sec ( 134 ms per call) imagemagick 2.2 sec ( 218 ms per call) pyqt5 1 sec ( 104 ms per call) pyside2 1 sec ( 101 ms per call) wx 0.34 sec ( 33 ms per call) pygdk3 0.23 sec ( 23 ms per call) mac_screencapture mac_quartz gnome_dbus gnome-screenshot 4.4 sec ( 437 ms per call) ``` -------------------------------- ### Get Backend Version Source: https://context7.com/ponty/pyscreenshot/llms.txt Check the version of installed backends for debugging and compatibility. ```python import pyscreenshot # Get version of specific backends for backend_name in pyscreenshot.backends(): version = pyscreenshot.backend_version(backend_name) if version: print(f"{backend_name}: {version}") else: print(f"{backend_name}: not installed") # Example output: # pil: 9.0.1 # mss: 7.0.1 # scrot: 1.7 # maim: 5.6.3 # imagemagick: 6.9.11 # pyqt5: 5.15.6 # pyside2: 5.15.2 ``` -------------------------------- ### backend_version() - Get Backend Version Source: https://context7.com/ponty/pyscreenshot/llms.txt Fetches the version string for a specified backend, useful for debugging and compatibility checks. ```APIDOC ## backend_version() - Get Backend Version Returns the version string of a specific backend, useful for debugging and compatibility checks. ```python import pyscreenshot # Get version of specific backends for backend_name in pyscreenshot.backends(): version = pyscreenshot.backend_version(backend_name) if version: print(f"{backend_name}: {version}") else: print(f"{backend_name}: not installed") # Example output: # pil: 9.0.1 # mss: 7.0.1 # scrot: 1.7 # maim: 5.6.3 # imagemagick: 6.9.11 # pyqt5: 5.15.6 # pyside2: 5.15.2 ``` ``` -------------------------------- ### List Available Backends Source: https://context7.com/ponty/pyscreenshot/llms.txt Retrieve a list of supported backends and verify their availability on the current system. ```python import pyscreenshot # Get list of all available backends available_backends = pyscreenshot.backends() print("Available backends:", available_backends) # Output: ['pil', 'mss', 'scrot', 'grim', 'maim', 'imagemagick', 'pyqt5', # 'pyside2', 'wx', 'pygdk3', 'mac_screencapture', 'mac_quartz', # 'freedesktop_dbus', 'gnome_dbus', 'gnome-screenshot'] # Try each backend for backend_name in available_backends: try: im = pyscreenshot.grab(backend=backend_name) print(f"{backend_name}: success ({im.size})") except pyscreenshot.FailedBackendError: print(f"{backend_name}: not available") ``` -------------------------------- ### Command Line Interface Usage Source: https://context7.com/ponty/pyscreenshot/llms.txt Execute common tasks like capturing screenshots, checking backend versions, and running benchmarks via the CLI. ```bash # Capture screenshot and save to file python -m pyscreenshot.cli.grab --filename screenshot.png # Capture specific region python -m pyscreenshot.cli.grab --filename region.png --bbox 0:0:500:500 # Force specific backend python -m pyscreenshot.cli.grab --filename capture.png --backend scrot # Show screenshot instead of saving python -m pyscreenshot.cli.grab --show # Check all backend versions python -m pyscreenshot.check.versions # Run performance benchmark python -m pyscreenshot.check.speedtest # Benchmark without subprocess (faster) python -m pyscreenshot.check.speedtest --childprocess 0 # Benchmark with virtual display (for headless testing) python -m pyscreenshot.check.speedtest --virtual_display ``` -------------------------------- ### Virtual Display Integration Source: https://context7.com/ponty/pyscreenshot/llms.txt Capture screenshots in headless environments using pyvirtualdisplay and Xvfb. ```python from time import sleep from easyprocess import EasyProcess from pyvirtualdisplay import Display import pyscreenshot as ImageGrab # Create virtual display and capture application window with Display(size=(800, 600)) as disp: # Launch application in virtual display with EasyProcess(["xmessage", "Hello World"]): sleep(1) # Wait for window to render img = ImageGrab.grab() img.save("virtual_capture.png") # Capture with specific display size with Display(size=(1920, 1080), visible=False) as disp: with EasyProcess(["firefox", "https://example.com"]): sleep(3) # Wait for page to load screenshot = ImageGrab.grab() screenshot.save("firefox_screenshot.png") # Headless testing with multiple captures def capture_app_states(app_command, delay=1, num_captures=5): """Capture multiple screenshots during application lifecycle.""" with Display(size=(1024, 768), visible=False): with EasyProcess(app_command): screenshots = [] for i in range(num_captures): sleep(delay) im = ImageGrab.grab(backend="mss", childprocess=False) screenshots.append(im) im.save(f"state_{i}.png") return screenshots ``` -------------------------------- ### Run test suite with Vagrant Source: https://github.com/ponty/pyscreenshot/blob/master/README.md Executes the test suite using the provided Vagrant configuration script. ```console $ ./tests/vagrant/vagrant_boxes.py ``` -------------------------------- ### Capture Fullscreen Source: https://github.com/ponty/pyscreenshot/blob/master/README.md Captures the entire screen and saves it as a PNG file. ```python # pyscreenshot/examples/grabfullscreen.py "Grab the whole screen" import pyscreenshot as ImageGrab # grab fullscreen im = ImageGrab.grab() # save image file im.save("fullscreen.png") ``` -------------------------------- ### Wayland Support Source: https://context7.com/ponty/pyscreenshot/llms.txt Basic import for Wayland-supported environments. ```python import pyscreenshot as ImageGrab import os ``` -------------------------------- ### backends() - List Available Backends Source: https://context7.com/ponty/pyscreenshot/llms.txt Retrieves a list of all backend names that can be utilized with the grab() function. ```APIDOC ## backends() - List Available Backends Returns a list of all available backend names that can be used with the grab() function. ```python import pyscreenshot # Get list of all available backends available_backends = pyscreenshot.backends() print("Available backends:", available_backends) # Output: ['pil', 'mss', 'scrot', 'grim', 'maim', 'imagemagick', 'pyqt5', # 'pyside2', 'wx', 'pygdk3', 'mac_screencapture', 'mac_quartz', # 'freedesktop_dbus', 'gnome_dbus', 'gnome-screenshot'] # Try each backend for backend_name in available_backends: try: im = pyscreenshot.grab(backend=backend_name) print(f"{backend_name}: success ({im.size})") except pyscreenshot.FailedBackendError: print(f"{backend_name}: not available") ``` ``` -------------------------------- ### Force Wayland Backend on GNOME Source: https://context7.com/ponty/pyscreenshot/llms.txt Attempts to capture a screenshot using the 'gnome_dbus' backend, specifically for GNOME Wayland environments. Includes error handling for failed captures. ```python if "GNOME" in os.environ.get("XDG_CURRENT_DESKTOP", ""): try: im = ImageGrab.grab(backend="gnome_dbus") im.save("gnome_wayland.png") except Exception as e: print(f"GNOME D-Bus failed: {e}") ``` -------------------------------- ### Capture Screenshots with grab() Source: https://context7.com/ponty/pyscreenshot/llms.txt Capture full screen or specific regions using bounding boxes, with options to specify backends and subprocess isolation. ```python import pyscreenshot as ImageGrab # Capture full screen im = ImageGrab.grab() im.save("fullscreen.png") # Capture specific region (x1, y1, x2, y2) im = ImageGrab.grab(bbox=(10, 10, 510, 510)) im.save("region.png") # Force specific backend im = ImageGrab.grab(backend="scrot") im.save("scrot_capture.png") # Best performance: disable subprocess isolation with fast backend im = ImageGrab.grab(backend="mss", childprocess=False) im.save("fast_capture.png") # Capture with Pillow backend im = ImageGrab.grab(backend="pil", childprocess=False) im.save("pil_capture.png") ``` -------------------------------- ### Force Grim Backend on Sway Source: https://context7.com/ponty/pyscreenshot/llms.txt Attempts to capture a screenshot using the 'grim' backend, specifically for Sway Wayland compositors. Includes error handling for failed captures. ```python if "sway" in os.environ.get("XDG_CURRENT_DESKTOP", "").lower(): try: im = ImageGrab.grab(backend="grim") im.save("sway_capture.png") except Exception as e: print(f"Grim failed: {e}") ``` -------------------------------- ### Check Display Server Type Source: https://context7.com/ponty/pyscreenshot/llms.txt This snippet checks the current session type and DISPLAY environment variables to understand the display server configuration. ```python session_type = os.environ.get("XDG_SESSION_TYPE", "") display = os.environ.get("DISPLAY", "") print(f"Session type: {session_type}") print(f"DISPLAY: {display}") ``` -------------------------------- ### Handle FailedBackendError Source: https://context7.com/ponty/pyscreenshot/llms.txt Implement fallback logic to try multiple backends if the preferred one fails. ```python import pyscreenshot from pyscreenshot import FailedBackendError def capture_with_fallback(preferred_backends=None): """Capture screenshot with fallback to other backends.""" if preferred_backends is None: preferred_backends = ["mss", "pil", "scrot"] for backend in preferred_backends: try: im = pyscreenshot.grab(backend=backend, childprocess=False) print(f"Success with {backend}") return im except FailedBackendError as e: print(f"Backend {backend} failed: {e}") continue # Fall back to automatic selection try: return pyscreenshot.grab() except FailedBackendError: raise RuntimeError("All screenshot backends failed") # Usage try: screenshot = capture_with_fallback() screenshot.save("screenshot.png") except RuntimeError as e: print(f"Error: {e}") ``` -------------------------------- ### Bounding Box Region Capture Source: https://context7.com/ponty/pyscreenshot/llms.txt Demonstrates capturing specific screen regions using bounding box coordinates. ```APIDOC ## Bounding Box Region Capture Capture specific screen regions using coordinates (x1, y1, x2, y2) where (x1, y1) is the top-left corner and (x2, y2) is the bottom-right corner. ```python import pyscreenshot as ImageGrab # Capture top-left 500x500 pixels im = ImageGrab.grab(bbox=(0, 0, 500, 500)) im.save("topleft.png") # Capture center region (assuming 1920x1080 screen) screen_width, screen_height = 1920, 1080 center_size = 400 x1 = (screen_width - center_size) // 2 y1 = (screen_height - center_size) // 2 x2 = x1 + center_size y2 = y1 + center_size im = ImageGrab.grab(bbox=(x1, y1, x2, y2)) im.save("center.png") ``` ``` -------------------------------- ### Optimize Performance with childprocess Parameter Source: https://context7.com/ponty/pyscreenshot/llms.txt Compare performance between safe mode (subprocess) and fast mode (main process). Setting childprocess=False is faster but may cause backend conflicts. ```python import pyscreenshot as ImageGrab import time # Safe mode (default): backends run in subprocess # Slower but isolated from each other start = time.time() for _ in range(10): im = ImageGrab.grab(backend="mss", childprocess=True) safe_time = time.time() - start print(f"Safe mode (subprocess): {safe_time:.2f}s for 10 captures") # Fast mode: backends run in main process # Much faster but potential conflicts start = time.time() for _ in range(10): im = ImageGrab.grab(backend="mss", childprocess=False) fast_time = time.time() - start print(f"Fast mode (no subprocess): {fast_time:.2f}s for 10 captures") # Typical output: # Safe mode (subprocess): 2.0s for 10 captures (~200ms each) # Fast mode (no subprocess): 0.2s for 10 captures (~20ms each) ``` -------------------------------- ### grab() - Capture Screenshots Source: https://context7.com/ponty/pyscreenshot/llms.txt The primary function to capture screenshots. It supports full screen, region capture, and manual backend selection. ```APIDOC ## grab() - Capture Screenshots The main function for capturing screen content. Supports full screen capture, region capture via bounding box, backend selection, and optional subprocess isolation for stability. ```python import pyscreenshot as ImageGrab # Capture full screen im = ImageGrab.grab() im.save("fullscreen.png") # Capture specific region (x1, y1, x2, y2) im = ImageGrab.grab(bbox=(10, 10, 510, 510)) im.save("region.png") # Force specific backend im = ImageGrab.grab(backend="scrot") im.save("scrot_capture.png") # Best performance: disable subprocess isolation with fast backend im = ImageGrab.grab(backend="mss", childprocess=False) im.save("fast_capture.png") # Capture with Pillow backend im = ImageGrab.grab(backend="pil", childprocess=False) im.save("pil_capture.png") ``` ``` -------------------------------- ### Working with Pillow Image Objects Source: https://context7.com/ponty/pyscreenshot/llms.txt Process captured screenshots using standard Pillow methods for filtering, resizing, and format conversion. ```python import pyscreenshot as ImageGrab from PIL import ImageFilter, ImageEnhance # Capture and process im = ImageGrab.grab() # Get image properties print(f"Size: {im.size}") # (width, height) print(f"Mode: {im.mode}") # 'RGB' print(f"Format: {im.format}") # None (in-memory) # Save in different formats im.save("screenshot.png") im.save("screenshot.jpg", quality=95) im.save("screenshot.webp", quality=90) im.save("screenshot.bmp") # Apply filters blurred = im.filter(ImageFilter.GaussianBlur(radius=5)) sharpened = im.filter(ImageFilter.SHARPEN) edges = im.filter(ImageFilter.FIND_EDGES) # Adjust image enhancer = ImageEnhance.Contrast(im) high_contrast = enhancer.enhance(1.5) brightness = ImageEnhance.Brightness(im) brightened = brightness.enhance(1.2) # Resize and thumbnail resized = im.resize((800, 600)) thumbnail = im.copy() thumbnail.thumbnail((200, 200)) # Convert to different modes grayscale = im.convert("L") rgba = im.convert("RGBA") # Get pixel data pixels = list(im.getdata()) rgb_array = im.tobytes() ``` -------------------------------- ### Force a specific pyscreenshot backend Source: https://github.com/ponty/pyscreenshot/blob/master/README.md This Python snippet shows how to explicitly select a backend (e.g., 'scrot') when capturing a screenshot using pyscreenshot. This is useful for ensuring consistent behavior or using a preferred backend. ```python import pyscreenshot as ImageGrab im = ImageGrab.grab(backend="scrot") ``` -------------------------------- ### Capture Multiple Screen Regions Source: https://context7.com/ponty/pyscreenshot/llms.txt Iterate through a dictionary of bounding boxes to capture and save specific screen areas. ```python regions = { "header": (0, 0, 1920, 100), "sidebar": (0, 100, 300, 1080), "content": (300, 100, 1920, 1080), } for name, bbox in regions.items(): im = ImageGrab.grab(bbox=bbox) im.save(f"{name}.png") ``` -------------------------------- ### Optimize pyscreenshot performance by disabling subprocess Source: https://github.com/ponty/pyscreenshot/blob/master/README.md This Python snippet demonstrates how to disable the subprocess for backends like 'mss' or 'pil' to achieve better performance. This setting is recommended for speed when stability is not a primary concern. ```python import pyscreenshot as ImageGrab im = ImageGrab.grab(backend="mss", childprocess=False) ``` -------------------------------- ### Capture Specific Regions Source: https://context7.com/ponty/pyscreenshot/llms.txt Define bounding boxes using (x1, y1, x2, y2) coordinates to capture specific screen areas. ```python import pyscreenshot as ImageGrab # Capture top-left 500x500 pixels im = ImageGrab.grab(bbox=(0, 0, 500, 500)) im.save("topleft.png") # Capture center region (assuming 1920x1080 screen) screen_width, screen_height = 1920, 1080 center_size = 400 x1 = (screen_width - center_size) // 2 y1 = (screen_height - center_size) // 2 x2 = x1 + center_size y2 = y1 + center_size im = ImageGrab.grab(bbox=(x1, y1, x2, y2)) im.save("center.png") ``` -------------------------------- ### FailedBackendError - Exception Handling Source: https://context7.com/ponty/pyscreenshot/llms.txt Handles exceptions raised when a screenshot backend fails, allowing for fallback mechanisms. ```APIDOC ## FailedBackendError - Exception Handling Exception raised when a backend fails to capture a screenshot. Handle this to implement fallback logic. ```python import pyscreenshot from pyscreenshot import FailedBackendError def capture_with_fallback(preferred_backends=None): """Capture screenshot with fallback to other backends.""" if preferred_backends is None: preferred_backends = ["mss", "pil", "scrot"] for backend in preferred_backends: try: im = pyscreenshot.grab(backend=backend, childprocess=False) print(f"Success with {backend}") return im except FailedBackendError as e: print(f"Backend {backend} failed: {e}") continue # Fall back to automatic selection try: return pyscreenshot.grab() except FailedBackendError: raise RuntimeError("All screenshot backends failed") # Usage try: screenshot = capture_with_fallback() screenshot.save("screenshot.png") except RuntimeError as e: print(f"Error: {e}") ``` ``` -------------------------------- ### Capture Screen Area Source: https://github.com/ponty/pyscreenshot/blob/master/README.md Captures a specific rectangular region of the screen defined by a bounding box. ```python # pyscreenshot/examples/grabbox.py "Grab the part of the screen" import pyscreenshot as ImageGrab # part of the screen im = ImageGrab.grab(bbox=(10, 10, 510, 510)) # X1,Y1,X2,Y2 # save image file im.save("box.png") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.