Getting Monitor resolution in Python on Ubuntu

12,026

Solution 1

I assume you're a GUI toolkit. Why else would you be interested in the screen dimensions?

Check out gtk.gdk.screen_width() and gtk.gdk.screen_height() from PyGTK. Something similar should be available for QT.

Solution 2

I can suggest a few approaches that can be used. I have not used the xlib version though.

1) xlib ( X client library for Python programs), if available on your system. You can look at "Display" methods and properties : python-xlib.sourceforge

2) On Ubuntu, you could do the following to get the screen resolution:

   xrandr  | grep \* | cut -d' ' -f4

3) You can use subprocess python module, to run the above command and extract the information

import subprocess
output = subprocess.Popen('xrandr | grep "\*" | cut -d" " -f4',shell=True, stdout=subprocess.PIPE).communicate()[0]
print output

Let me know, if this was helpful to you.

Solution 3

import subprocess


def get_screen_resolution():
    output = subprocess.Popen('xrandr | grep "\*" | cut -d" " -f4',shell=True, stdout=subprocess.PIPE).communicate()[0]
    resolution = output.split()[0].split(b'x')
    return {'width': resolution[0], 'height': resolution[1]}

print(get_screen_resolution())

The resolution[0] would be Byte format like b'1020'. To convert this to Integer format, please try int(resolution[0].decode('UTF-8')).

Solution 4

pyautogui makes the work simple.

import pyautogui
pyautogui.size()

will fetch your screen resolution as a tuple containing (width, height)

Solution 5

I'm using python 3.5 on Ubuntu 16.04 LTS and had the same problem. I wanted to solve it without having to rely on extra modules because they aren't installed by default.

So I imagined this small function, which uses xrandr to get the data.

def monitorsInfo():

import subprocess

def getParenthesis(texte):
    content = None
    p1 = texte.find('(')
    if p1 >= 0:
        p2 = texte.find(')')
        if p2 > p1:
            content = texte[p1:p2+1]
    return content

commande = ['xrandr','--listmonitors']
res = subprocess.check_output(commande, shell=True).decode().split('\n')

monitors = {}

for l in res:
    if len(l) > 1:
        if l[0] != ' ':
            if l.split()[0] == l.split()[0].upper():

                options = getParenthesis(l)
                if options:
                    l = l.replace(options, '')
                z = l.split()

                # this is a connector
                name = z[0]
                conn = None
                primary = None
                geo = None
                size = None
                width = height = offsetx = offsety = None
                if z[1].lower() == 'connected':
                    conn = True
                    # monitor in use :-)
                else:
                    # screeen connection exists, no screen used
                    conn = False
                # for connected screens : get extra data
                if conn:
                    if z[2].lower() == 'primary':
                        primary = True
                        z.pop(2)
                    # other data for connected screeens
                    geo = z[2]   # get rid of extra 'primary'
                    size = ''.join(z[3:])
                    # get width and height
                    z = geo.split('+')
                    offsetx = int(z[1])
                    offsety = int(z[2])
                    z = z[0].split('x')
                    width = int(z[0])
                    height = int(z[1])


                # create a dict per monitor
                d = {}
                d['name'] = name
                d['connected'] = conn
                d['primary'] = primary
                d['geometry'] = geo
                d['options'] = options
                d['size'] = size
                d['width'] = width
                d['height'] = height
                d['offsetx'] = offsetx
                d['offsety'] = offsety

                monitors[name] = d

return monitors

The result is returned as a dictionary.

Share:
12,026
rectangletangle
Author by

rectangletangle

Updated on June 04, 2022

Comments

  • rectangletangle
    rectangletangle almost 2 years

    Is there a equatable bit of code to GetSystemMetrics in win32api, for Ubuntu? I need to get the monitors width and height in pixels.