How can I list connected monitor(s) with xrandr?
I'm working on developing a python application for Ubuntu that enables a user to have their desired resolution without requiring graphics drivers.
In order to do this I've been using xrandr
, which so far, has been pretty useful
However, I now have a problem; how can I detect the monitor name? I was intending to use a terminal command through os.system
, modifying the terminal output to get the required monitor output, and then storing it within the program. Unfortunately, despite much searching, I have been unable to find out how I can do this.
Is there any way in which I can do this?
To sum it up: I'm looking for a terminal command that gives me the monitor name, such VGA1
or DVI-0
Solution 1:
I am not sure how you are going to apply it in your application ("enable a user to have their desired resolution without requiring graphics drivers" ?), but:
A terminal command to list connected screens
xrandr | grep " connected " | awk '{ print$1 }'
This wil give you the connected screens for further processing, like:
VGA-0
DVI-I-1
Since you mention python, the snippet below will also list connected screens:
#!/usr/bin/env python3
import subprocess
def screens():
output = [l for l in subprocess.check_output(["xrandr"]).decode("utf-8").splitlines()]
return [l.split()[0] for l in output if " connected " in l]
print(screens())
This wil also give you the connected screens, like:
['VGA-0', 'DVI-I-1']
Note
Note the spaces around " connected "
in the searched string. They are needed to prevent mismatches with disconnected
.
EDIT 2019
Using python, not necessary to use xrandr
or any other system call at all. Better use Gdk:
#!/usr/bin/env python3
import gi
gi.require_version("Gdk", "3.0")
from gi.repository import Gdk
allmonitors = []
gdkdsp = Gdk.Display.get_default()
for i in range(gdkdsp.get_n_monitors()):
monitor = gdkdsp.get_monitor(i)
scale = monitor.get_scale_factor()
geo = monitor.get_geometry()
allmonitors.append([
monitor.get_model()] + [n * scale for n in [
geo.x, geo.y, geo.width, geo.height
]
])
print(allmonitors)
Example output:
[['eDP-1', 0, 0, 3840, 2160], ['DP-2', 3840, 562, 1680, 1050]]
Depending on the desired info, you can make your choice from https://lazka.github.io/pgi-docs/Gdk-3.0/classes/Monitor.html
Solution 2:
You can use the bash command with popen:
import os
list_display = os.popen("xrandr --listmonitors | grep '*' | awk {'print $4'}").read().splitlines()
# or based on the comment of this answer
list_display = os.popen("xrandr --listmonitors | grep '+' | awk {'print $4'}").read().splitlines()
or I wrote a old gist on the subject https://gist.github.com/antoinebou13/7a212ccd84cc95e040b2dd0e14662445