importing pyautogui in ubuntu throwing KEYERROR :DISPLAY

Viewed 24676
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
4 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

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())

It seems you can't use Display. To fix this type this in your bash terminal:

export DISPLAY=:0

This should fix it. Now you can run your pyautogui code:

import pyautogui

pyautogui.moveTo(100, 200)
pyautogui.moveTo(200, 300)
#And so on...

Looks like you are installing python 3 libraries but you are running python 2.7.

To use pyautogui in python 2.7, replace:

  • pip install python3-xlib with pip install python-xlib
  • sudo apt-get install python3-tk with sudo apt-get install python-tk

You may or may not need the dev tools, but try those changes first and let me know if that works.

Related