Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

importing pyautogui in ubuntu throwing KEYERROR :DISPLAY

Traceback (most recent call last):
  File "1.py", line 1, in <module>
    import pyautogui
  File "/home/prasoon/.local/lib/python2.7/site-packages/pyautogui/__init__.py", line 115, in <module>
    from . import _pyautogui_x11 as platformModule
  File "/home/prasoon/.local/lib/python2.7/site-packages/pyautogui/_pyautogui_x11.py", line 160, in <module>
    _display = Display(os.environ['DISPLAY'])
  File "/usr/lib/python2.7/UserDict.py", line 40, in __getitem__
    raise KeyError(key)
KeyError: 'DISPLAY'

Python version- Python 2.7.15rc1

While running "import pyautogui" this error is being thrown

I run the following commands -

pip install `python3-xlib`

sudo apt-get install scrot

sudo apt-get install python3-tk

sudo apt-get install python3-dev

pip install pyautogui
like image 269
Prasoon Singh Avatar asked Sep 09 '18 11:09

Prasoon Singh


People also ask

What is KeyError display in Python?

A Python KeyError exception is what is raised when you try to access a key that isn't in a dictionary ( dict ). Python's official documentation says that the KeyError is raised when a mapping key is accessed and isn't found in the mapping. A mapping is a data structure that maps one set of values to another.


2 Answers

You have to correctly set environment variable DISPLAY. It should be defined by your OS. If it's not, you can define it manually.

Option 1 - run python with:

DISPLAY=:0 python

Option 2 - set environment variable in Python

import os

os.environ['DISPLAY'] = ':0'

Option 3 - put it to you .bashrc file

echo "DISPLAY=:0" >> ~/.bashrc
source ~/.bashrc
like image 97
jozo Avatar answered Sep 17 '22 05:09

jozo


Debian 10. crontab RUN pyautogui script to GNOME Screen

import os
os.environ['DISPLAY'] = ':0'
os.environ['XAUTHORITY']='/run/user/1000/gdm/Xauthority'
import pyautogui
print(pyautogui.position())
like image 34
Aaz Avatar answered Sep 17 '22 05:09

Aaz