### Basic Virtual Display Management with Display Class Source: https://context7.com/ponty/pyvirtualdisplay/llms.txt Demonstrates the core functionality of the Display class for creating and managing virtual X servers using a context manager. It shows how to start a display, retrieve its details, and run a GUI application within it. Includes examples for both recommended context manager usage and manual start/stop control. ```python from pyvirtualdisplay import Display from easyprocess import EasyProcess # Create invisible Xvfb display with context manager (recommended) with Display(visible=False, size=(1024, 768), color_depth=24) as disp: print(f"Display started: {disp.new_display_var}") print(f"PID: {disp.pid}") print(f"Is alive: {disp.is_alive()}") # True # Run GUI application on virtual display with EasyProcess(["xmessage", "Hello World"]) as proc: proc.wait() print(f"Display stopped, is alive: {disp.is_alive()}") # False # Alternative: Manual start/stop (not recommended) disp = Display(backend="xvfb", size=(800, 600)) disp.start() # ... use display ... disp.stop() ``` -------------------------------- ### Run VNC Server Example (Python) Source: https://github.com/ponty/pyvirtualdisplay/blob/master/README.md Starts a virtual VNC server using pyvirtualdisplay and runs 'xmessage'. This allows a VNC client to connect and view the displayed message. ```python # pyvirtualdisplay/examples/vncserver.py "Start virtual VNC server. Connect with: vncviewer localhost:5904" from easyprocess import EasyProcess from pyvirtualdisplay import Display with Display(backend="xvnc", size=(100, 60), rfbport=5904) as disp: with EasyProcess(["xmessage", "hello"]) as proc: proc.wait() ``` -------------------------------- ### Install pyvirtualdisplay and Dependencies Source: https://github.com/ponty/pyvirtualdisplay/blob/master/README.md Installs the pyvirtualdisplay package and optional dependencies like Pillow and EasyProcess for enhanced functionality. Also includes system package installation commands for Ubuntu. ```console python3 -m pip install pyvirtualdisplay python3 -m pip install pillow python3 -m pip install EasyProcess sudo apt-get install xvfb xserver-xephyr tigervnc-standalone-server x11-utils gnumeric ``` -------------------------------- ### Visible Xephyr Display Setup Source: https://context7.com/ponty/pyvirtualdisplay/llms.txt Utilize XephyrDisplay to create a visible nested X server, allowing for specification of parent windows and resizeable window support for interactive debugging. ```python from pyvirtualdisplay.xephyr import XephyrDisplay # Basic Xephyr display with XephyrDisplay( size=(1024, 768), color_depth=24, bgcolor="black", use_xauth=False ) as disp: print(f"Xephyr window opened: {disp.new_display_var}") input("Press Enter to close display...") ``` -------------------------------- ### VNC Server Display Setup Source: https://context7.com/ponty/pyvirtualdisplay/llms.txt Illustrates how to create remotely accessible virtual displays using the 'xvnc' backend. It covers setting up a VNC server both without password authentication (for testing) and with password authentication using an `rfbauth` file for secure remote access. The `easyprocess` library is used to run applications on the VNC display. Requires `pyvirtualdisplay` and `easyprocess`. ```python from pyvirtualdisplay import Display from easyprocess import EasyProcess import time # VNC server without password (for testing only) with Display( backend="xvnc", size=(1024, 768), color_depth=24, rfbport=5901 ) as disp: print(f"VNC server started on display {disp.new_display_var}") print(f"Connect with: vncviewer localhost:5901") print(f"Process PID: {disp.pid}") # Run application on VNC display with EasyProcess(["xclock"]) as proc: time.sleep(30) # Keep alive for 30 seconds # VNC server with password file with Display( backend="xvnc", size=(1280, 720), rfbport=5902, rfbauth="/path/to/vncpasswd/file" ) as disp: print(f"Secure VNC server on port 5902") # Application runs here ``` -------------------------------- ### Control Display with start() and stop() (Python) Source: https://github.com/ponty/pyvirtualdisplay/blob/master/README.md Shows an alternative method to control the virtual display using explicit start() and stop() calls. This method is not recommended due to potential issues with managing the display lifecycle. ```python from pyvirtualdisplay import Display disp = Display() disp.start() # display is active disp.stop() # display is stopped ``` -------------------------------- ### Nested Xephyr Servers Source: https://github.com/ponty/pyvirtualdisplay/blob/master/README.md Demonstrates creating nested Xephyr virtual displays with different background colors and sizes. An 'xmessage' window is displayed within the innermost display. This example requires EasyProcess and PyVirtualDisplay. ```python # pyvirtualdisplay/examples/nested.py "Nested Xephyr servers" from easyprocess import EasyProcess from pyvirtualdisplay import Display with Display(visible=True, size=(220, 180), bgcolor="black"): with Display(visible=True, size=(200, 160), bgcolor="white"): with Display(visible=True, size=(180, 140), bgcolor="black"): with Display(visible=True, size=(160, 120), bgcolor="white"): with Display(visible=True, size=(140, 100), bgcolor="black"): with Display(visible=True, size=(120, 80), bgcolor="white"): with Display(visible=True, size=(100, 60), bgcolor="black"): with EasyProcess(["xmessage", "hello"]) as proc: proc.wait() ``` -------------------------------- ### Backend Selection for Virtual Displays Source: https://context7.com/ponty/pyvirtualdisplay/llms.txt Illustrates how to explicitly select different backend X servers (Xvfb, Xephyr, Xvnc) for virtual displays. Each backend offers distinct features: Xvfb for headless operation, Xephyr for visible nested servers, and Xvnc for VNC-accessible remote displays. Examples include setting specific parameters like background color and VNC port. ```python from pyvirtualdisplay import Display # Xvfb backend (default, invisible) with Display(backend="xvfb", size=(1920, 1080)) as disp: print(f"Invisible display: {disp.new_display_var}") # Xephyr backend (visible, nested X server) with Display(backend="xephyr", size=(800, 600), bgcolor="white") as disp: print(f"Visible display opens window: {disp.new_display_var}") # You can see the nested window on your desktop input("Press Enter to close...") # Xvnc backend (VNC server, remotely accessible) with Display(backend="xvnc", size=(1024, 768), rfbport=5904) as disp: print(f"VNC server on port 5904: {disp.new_display_var}") print("Connect with: vncviewer localhost:5904") input("Press Enter to close...") ``` -------------------------------- ### Headless Run with xmessage (Python) Source: https://github.com/ponty/pyvirtualdisplay/blob/master/README.md Executes 'xmessage' on a hidden virtual display created with pyvirtualdisplay. This example is useful for running GUI applications without a visible screen. ```python # pyvirtualdisplay/examples/headless.py "Start Xvfb server. Open xmessage window." from easyprocess import EasyProcess from pyvirtualdisplay import Display with Display(visible=False, size=(100, 60)) as disp: with EasyProcess(["xmessage", "hello"]) as proc: proc.wait() ``` -------------------------------- ### Set Display Size (Python) Source: https://github.com/ponty/pyvirtualdisplay/blob/master/README.md Configures the resolution of the virtual display during its creation. This example sets the display to 100 pixels wide and 60 pixels high. ```python disp=Display(size=(100, 60)) ``` -------------------------------- ### Nested Xephyr Displays for Debugging Source: https://context7.com/ponty/pyvirtualdisplay/llms.txt Provides an example of creating multiple nested virtual displays using Xephyr. Each display is visible and appears as a window within the parent display, which is useful for visual debugging or demonstrations. The code demonstrates creating three nested displays with different sizes and background colors, and running an application (`xeyes`) within the innermost display. Requires `pyvirtualdisplay` and `easyprocess`. ```python from pyvirtualdisplay import Display from easyprocess import EasyProcess # Create nested displays with different sizes and colors with Display(visible=True, size=(800, 600), bgcolor="black") as outer: print(f"Outer display: {outer.new_display_var}") with Display(visible=True, size=(600, 400), bgcolor="white") as middle: print(f"Middle display: {middle.new_display_var}") with Display(visible=True, size=(400, 200), bgcolor="black") as inner: print(f"Inner display: {inner.new_display_var}") # Run application in innermost display with EasyProcess(["xeyes"]) as proc: proc.wait() ``` -------------------------------- ### Control Display with Context Manager (Python) Source: https://github.com/ponty/pyvirtualdisplay/blob/master/README.md Demonstrates using pyvirtualdisplay.Display as a context manager to automatically start and stop a virtual display. The display is active within the 'with' block and stopped upon exiting. ```python from pyvirtualdisplay import Display with Display() as disp: # display is active print(disp.is_alive()) # True # display is stopped print(disp.is_alive()) # False ``` -------------------------------- ### Set Display Color Depth (Python) Source: https://github.com/ponty/pyvirtualdisplay/blob/master/README.md Specifies the color depth for the virtual display. This example sets the color depth to 24 bits per pixel. ```python disp=Display(color_depth=24) ``` -------------------------------- ### Screenshot Capture with SmartDisplay Source: https://context7.com/ponty/pyvirtualdisplay/llms.txt Details the SmartDisplay class, which extends Display with screenshot capabilities using the Pillow library. The `waitgrab` method is highlighted for capturing screenshots after content appears, with automatic background cropping. An example of manual screenshot capture using `grab` is also provided. ```python from pyvirtualdisplay.smartdisplay import SmartDisplay from easyprocess import EasyProcess # Capture screenshot of GUI application with SmartDisplay(visible=False, size=(800, 600), bgcolor="black") as disp: with EasyProcess(["xmessage", "Screenshot me!"]): # Wait for window to appear and grab screenshot # Automatically crops black background img = disp.waitgrab(timeout=10, autocrop=True) # Save screenshot img.save("screenshot.png") print(f"Screenshot saved: {img.size}") # Manual screenshot without waiting with SmartDisplay() as disp: with EasyProcess(["gnumeric"]): import time time.sleep(2) # Wait for app to render img = disp.grab(autocrop=True) img.save("gnumeric.png") ``` -------------------------------- ### Thread-Safe Display Management Source: https://github.com/ponty/pyvirtualdisplay/blob/master/README.md Illustrates how to manage virtual displays in a thread-safe manner using PyVirtualDisplay. It starts multiple 'xmessage' windows concurrently, each in its own thread, by setting manage_global_env to False and using disp.env() for process environments. Screenshots are saved for each message. ```python # pyvirtualdisplay/examples/threadsafe.py "Start Xvfb server and open xmessage window. Thread safe." import threading from easyprocess import EasyProcess from pyvirtualdisplay.smartdisplay import SmartDisplay def thread_function(index): # manage_global_env=False is thread safe with SmartDisplay(manage_global_env=False) as disp: cmd = ["xmessage", str(index)] # disp.new_display_var should be used for new processes # disp.env() copies global os.environ and adds disp.new_display_var with EasyProcess(cmd, env=disp.env()): img = disp.waitgrab() img.save("xmessage{}.png".format(index)) t1 = threading.Thread(target=thread_function, args=(1,)) t2 = threading.Thread(target=thread_function, args=(2,)) t1.start() t2.start() t1.join() t2.join() ``` -------------------------------- ### Accessing Display Environment Variables Source: https://context7.com/ponty/pyvirtualdisplay/llms.txt Demonstrates how to access display-specific environment variables and properties provided by `pyvirtualdisplay`. It shows how to retrieve the display number, display variable string, process ID, and check if the display is running. The `disp.env()` method is used to get an environment dictionary suitable for passing to subprocesses, ensuring they use the correct display. Requires `pyvirtualdisplay`, `subprocess`, and `os`. ```python from pyvirtualdisplay import Display import subprocess import os with Display(visible=False, size=(1024, 768)) as disp: # Access display properties print(f"Display number: {disp.display}") print(f"Display variable: {disp.new_display_var}") print(f"Process ID: {disp.pid}") print(f"Is running: {disp.is_alive()}") # Get environment dict for subprocess env = disp.env() print(f"DISPLAY in env: {env['DISPLAY']}") # Use with subprocess result = subprocess.run( ["xdpyinfo"], env=env, capture_output=True, text=True ) print(f"Display info: {result.stdout[:200]}") # Manual DISPLAY variable access # (when manage_global_env=True, os.environ is updated automatically) if disp._manage_global_env: print(f"Global DISPLAY: {os.environ.get('DISPLAY')}") ``` -------------------------------- ### Select Xvfb Backend (Python) Source: https://github.com/ponty/pyvirtualdisplay/blob/master/README.md Illustrates different ways to instantiate a Display object using the 'xvfb' backend. This is the default backend if not specified otherwise. ```python disp=Display() # or disp=Display(visible=False) # or disp=Display(backend="xvfb") ``` -------------------------------- ### Error Handling for Display Startup and Screenshots Source: https://context7.com/ponty/pyvirtualdisplay/llms.txt Implement robust error handling for display startup failures (XStartError, XStartTimeoutError) and screenshot capture timeouts (DisplayTimeoutError) to ensure stable automation. ```python from pyvirtualdisplay import Display from pyvirtualdisplay.smartdisplay import SmartDisplay, DisplayTimeoutError from pyvirtualdisplay.abstractdisplay import XStartError, XStartTimeoutError from easyprocess import EasyProcess # Handle display start errors try: with Display( backend="xvfb", size=(800, 600), retries=5, timeout=30 ) as disp: print(f"Display started: {disp.new_display_var}") except XStartError as e: print(f"Failed to start display: {e}") except XStartTimeoutError as e: print(f"Display start timeout: {e}") # Handle screenshot timeout try: with SmartDisplay() as disp: with EasyProcess(["true"]): # Command that exits immediately img = disp.waitgrab(timeout=5) except DisplayTimeoutError as e: print(f"Screenshot timeout: {e}") # Check if display is alive with Display() as disp: if disp.is_alive(): print("Display is running") else: print("Display failed to start") ``` -------------------------------- ### Select Xvnc Backend (Python) Source: https://github.com/ponty/pyvirtualdisplay/blob/master/README.md Shows how to instantiate a Display object using the 'xvnc' backend. This is suitable for scenarios where VNC clients need to connect to the virtual display. ```python disp=Display(backend="xvnc") ``` -------------------------------- ### Configuring Display Properties Source: https://context7.com/ponty/pyvirtualdisplay/llms.txt Shows how to customize various properties of the virtual display, such as resolution, color depth, and background color. It also demonstrates passing extra arguments directly to the underlying X server and configuring advanced options like Xauthority file usage, retries, and timeouts. ```python from pyvirtualdisplay import Display # Configure display properties with Display( backend="xvfb", size=(1280, 720), color_depth=16, bgcolor="black", extra_args=["-nocursor", "-dpi", "96"], use_xauth=True, # Generate Xauthority file retries=10, # Retry attempts if display allocation fails timeout=600 # Timeout in seconds ) as disp: print(f"Display: {disp.new_display_var}") print(f"Display number: {disp.display}") ``` -------------------------------- ### GUI Test with Gnumeric (Python) Source: https://github.com/ponty/pyvirtualdisplay/blob/master/README.md Launches Gnumeric on a low-resolution virtual display using Xephyr. This demonstrates GUI testing capabilities in a controlled environment. ```python # pyvirtualdisplay/examples/lowres.py "Testing gnumeric on low resolution." from easyprocess import EasyProcess from pyvirtualdisplay import Display # start Xephyr with Display(visible=True, size=(320, 240)) as disp: # start Gnumeric with EasyProcess(["gnumeric"]) as proc: proc.wait() ``` -------------------------------- ### Create Screenshot with SmartDisplay (Python) Source: https://github.com/ponty/pyvirtualdisplay/blob/master/README.md Uses the 'smartdisplay' submodule to capture a screenshot of an application running on a virtual display. This is useful for automated documentation or visual verification. ```python # pyvirtualdisplay/examples/screenshot.py "Create screenshot of xmessage in background using 'smartdisplay' submodule" from easyprocess import EasyProcess from pyvirtualdisplay.smartdisplay import SmartDisplay # 'SmartDisplay' instead of 'Display' # It has 'waitgrab()' method. ``` -------------------------------- ### Select Xephyr Backend (Python) Source: https://github.com/ponty/pyvirtualdisplay/blob/master/README.md Demonstrates how to select the 'xephyr' backend for the virtual display. Xephyr allows for a visible, nested display, useful for debugging or interactive use. ```python disp=Display(visible=True) # or disp=Display(backend="xephyr") ``` -------------------------------- ### Screenshot with SmartDisplay Source: https://github.com/ponty/pyvirtualdisplay/blob/master/README.md Captures a screenshot of a virtual display after a message is displayed. It utilizes SmartDisplay and EasyProcess. The output is saved as a PNG image. ```python from easyprocess import EasyProcess from pyvirtualdisplay.smartdisplay import SmartDisplay with SmartDisplay() as disp: with EasyProcess(["xmessage", "hello"]): # wait until something is displayed on the virtual display (polling method) # and then take a fullscreen screenshot # and then crop it. Background is black. img = disp.waitgrab() img.save("xmessage.png") ``` -------------------------------- ### Advanced Xvfb Display Configuration Source: https://context7.com/ponty/pyvirtualdisplay/llms.txt Configure XvfbDisplay with advanced options like framebuffer directory mapping, DPI settings, and extra arguments for precise control over the virtual framebuffer. ```python from pyvirtualdisplay.xvfb import XvfbDisplay # Advanced Xvfb configuration with XvfbDisplay( size=(1920, 1080), color_depth=24, bgcolor="white", fbdir="/tmp/xvfb_screens", # Map framebuffer to file dpi=96, # Set screen DPI use_xauth=True, extra_args=["-nocursor", "-nolisten", "tcp"] ) as disp: print(f"Xvfb display: {disp.new_display_var}") print(f"Framebuffer dir: /tmp/xvfb_screens") # Virtual display with memory-mapped framebuffer ``` -------------------------------- ### Thread-Safe Display Management Source: https://context7.com/ponty/pyvirtualdisplay/llms.txt Shows how to manage virtual displays in a thread-safe manner by disabling global environment management (`manage_global_env=False`) and using `disp.env()` to pass display-specific environment variables to subprocesses. This prevents race conditions when multiple threads access displays concurrently. Dependencies include `threading`, `pyvirtualdisplay`, and `easyprocess`. ```python import threading from pyvirtualdisplay.smartdisplay import SmartDisplay from easyprocess import EasyProcess def create_screenshot(index): # manage_global_env=False makes it thread-safe with SmartDisplay( manage_global_env=False, size=(400, 300), bgcolor="white" ) as disp: # Use disp.env() to get environment with correct DISPLAY cmd = ["xmessage", f"Thread {index}"] with EasyProcess(cmd, env=disp.env()): img = disp.waitgrab(timeout=10) img.save(f"thread_{index}.png") print(f"Thread {index}: Display {disp.new_display_var}, PID {disp.pid}") # Create multiple displays concurrently threads = [] for i in range(5): t = threading.Thread(target=create_screenshot, args=(i,)) threads.append(t) t.start() for t in threads: t.join() print("All screenshots created successfully") ``` -------------------------------- ### Custom Image Validation with waitgrab Source: https://context7.com/ponty/pyvirtualdisplay/llms.txt Demonstrates using callback functions with `disp.waitgrab` to perform custom validation on screenshots. This is useful for applications with dynamic loading states, ensuring screenshots are captured only when specific screen content criteria are met. It requires `pyvirtualdisplay` and `easyprocess`. ```python from pyvirtualdisplay.smartdisplay import SmartDisplay from easyprocess import EasyProcess def check_image_size(img): """Accept screenshot only if it's large enough""" width, height = img.size min_size = 100 return width > min_size and height > min_size def check_image_color(img): """Accept screenshot only if it contains non-black pixels""" colors = img.getcolors() return colors is not None and len(colors) > 1 with SmartDisplay(visible=False, bgcolor="black") as disp: with EasyProcess(["xterm", "-e", "echo 'Loading...'; sleep 1; echo 'Ready!'"]): # Wait until image meets custom criteria img = disp.waitgrab( timeout=30, autocrop=True, cb_imgcheck=check_image_size ) img.save("validated_screenshot.png") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.