PyVirtualDisplay

3.0 · active · verified Sat Apr 11

PyVirtualDisplay is a Python wrapper for Xvfb, Xephyr, and Xvnc programs. It enables running graphical applications or tests in a headless environment by creating a virtual display, making it suitable for CI/CD pipelines and automated GUI testing. The library is currently at version 3.0 and supports Python versions 3.6 through 3.12.

Warnings

Install

Imports

Quickstart

This example demonstrates how to start and stop a virtual display using a context manager. It sets up an Xvfb backend with a specific resolution and ensures the display is properly managed. The `visible=0` argument ensures the display runs in headless mode.

from pyvirtualdisplay import Display
import time
import os

# Ensure Xvfb or a similar X server is installed on the OS
# Example for Linux: sudo apt-get install xvfb

# For thread-safe operations in concurrent environments, use manage_global_env=False
# and explicitly set os.environ['DISPLAY'] if needed within the thread/process.
# For simple, single-threaded use, the default is often sufficient.
with Display(visible=0, size=(1920, 1080), backend='xvfb') as disp:
    print(f"Virtual display started on: {os.environ.get('DISPLAY')}")
    print(f"Is display alive: {disp.is_alive()}")
    # Simulate doing some work that requires a display
    time.sleep(2)
    print(f"Work done within virtual display. Is display still alive: {disp.is_alive()}")

print(f"Virtual display stopped. Is display alive: {disp.is_alive()}")
# os.environ['DISPLAY'] is restored to its original value after context manager exits

view raw JSON →