Skip to content

Instantly share code, notes, and snippets.

@fphammerle
Created January 21, 2018 15:33
Show Gist options
  • Save fphammerle/e83bb9abc326787238c5755109a18062 to your computer and use it in GitHub Desktop.
Save fphammerle/e83bb9abc326787238c5755109a18062 to your computer and use it in GitHub Desktop.
Display names of outputs available to the X server by accessing the xrandr extension via python's ctypes
#!/usr/bin/env python3
"""
Display names of outputs available to the X server similiar to 'xrandr' command.
Access xlib and xrandr extension via python's ctypes library.
tags: x11, xorg, x.org, xwindow-system, xlib, libx, xrandr, outputs, monitor, display
"""
import ctypes
import sys
Time = ctypes.c_ulong
XID = ctypes.c_ulong
RROutput = XID
RRCrtc = XID
RRMode = XID
Connection = ctypes.c_ushort
SubpixelOrder = ctypes.c_ushort
class XRRScreenResources(ctypes.Structure):
_fields_ = [
('timestamp', Time),
('configTimestamp', Time),
('ncrtc', ctypes.c_int),
('crtcs', ctypes.POINTER(RRCrtc)),
('noutput', ctypes.c_int),
('outputs', ctypes.POINTER(RROutput)),
('nmode', ctypes.c_int),
('modes', ctypes.c_void_p), # ctypes.POINTER(XRRModeInfo)
]
class XRROutputInfo(ctypes.Structure):
_fields_ = [
('timestamp', Time),
('crtc', RRCrtc),
('name', ctypes.c_char_p),
('nameLen', ctypes.c_int),
('mm_width', ctypes.c_ulong),
('mm_height', ctypes.c_ulong),
('connection', Connection),
('subpixel_order', SubpixelOrder),
('ncrtc', ctypes.c_int),
('crtcs', ctypes.POINTER(RRCrtc)),
('nclone', ctypes.c_int),
('clones', ctypes.POINTER(RROutput)),
('nmode', ctypes.c_int),
('npreferred', ctypes.c_int),
('modes', ctypes.POINTER(RRMode)),
]
X11 = ctypes.cdll.LoadLibrary("libX11.so")
Xrandr = ctypes.cdll.LoadLibrary("libXrandr.so")
Xrandr.XRRGetScreenResourcesCurrent.restype = ctypes.POINTER(XRRScreenResources)
Xrandr.XRRGetOutputInfo.restype = ctypes.POINTER(XRROutputInfo)
xdisplay = X11.XOpenDisplay(None)
root_window = X11.XDefaultRootWindow(xdisplay)
screen_resources = Xrandr.XRRGetScreenResourcesCurrent(xdisplay, root_window)
assert isinstance(screen_resources.contents, XRRScreenResources)
for o in range(screen_resources.contents.noutput):
output_info = Xrandr.XRRGetOutputInfo(xdisplay, screen_resources, screen_resources.contents.outputs[o])
print(output_info.contents.name.decode(sys.getfilesystemencoding()))
X11.XCloseDisplay(xdisplay)
@fphammerle
Copy link
Author

example output:

$ python3 xlib-xrandr-ctypes-print-output-names.py
eDP1
DP1
DP2
HDMI1
HDMI2
VGA1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment