How to fix KeyError: 'DISPLAY' in Python

Lucas123 picture Lucas123 · Mar 15, 2018 · Viewed 9.1k times · Source

I am using mss library in Python to take a screenshot and save it on the current path. It is working perfectly on my Mac using PyCharm. But when I try to run the same thing on Ubuntu 16 I get an error, even when I am doing exactly as the Docs says:

>>> from mss import mss
>>> with mss() as sct:
...     sct.shot()

but I am getting this error, how to fix this ?

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/mss/linux.py", line 132, in __init__
    display = os.environ['DISPLAY'].encode('utf-8')
  File "/usr/lib/python3.5/os.py", line 725, in __getitem__
    raise KeyError(key) from None
KeyError: 'DISPLAY'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/dist-packages/mss/factory.py", line 34, in mss
    return MSS(**kwargs)
  File "/usr/local/lib/python3.5/dist-packages/mss/linux.py", line 134, in __init__
    raise ScreenShotError('$DISPLAY not set.', locals())
mss.exception.ScreenShotError: ('$DISPLAY not set.', {'display': None, 'self': <mss.linux.MSS object at 0x7f06ce881d30>})

Answer

Tiger-222 picture Tiger-222 · May 7, 2018

Indeed, on GNU/Linux you must have the DISPLAY envar set. If not, it is not common and you could try setting the display keyword argument like:

>>> with mss(display=':0') as sct:
...     sct.shot()