skip to Main Content

I’m new to python+linux and somewhat stuck. I’m using Ubuntu 22.04 LTS, created this simplistic script:

import pyautogui
import keyboard

def on_key_event(e):
    if e.name == '1':
        pyautogui.press('h')
        pyautogui.press('k')
keyboard.hook(on_key_event)

#should keep running untill I press "Esc"
keyboard.wait('esc')
keyboard.unhook_all()

when i’m trying to run it with python3 test.py i’m getting this:

Traceback (most recent call last):
  File "/home/onetwothree/work/sandbox/PY/test.py", line 14, in <module>
    keyboard.hook(on_key_event)
  File "/home/onetwothree/.local/lib/python3.10/site-packages/keyboard/__init__.py", line 461, in hook
    append(callback)
  File "/home/onetwothree/.local/lib/python3.10/site-packages/keyboard/_generic.py", line 67, in add_handler
    self.start_if_necessary()
  File "/home/onetwothree/.local/lib/python3.10/site-packages/keyboard/_generic.py", line 35, in start_if_necessary
    self.init()
  File "/home/naww/.local/lib/python3.10/site-packages/keyboard/__init__.py", line 196, in init
    _os_keyboard.init()
  File "/home/onetwothree/.local/lib/python3.10/site-packages/keyboard/_nixkeyboard.py", line 113, in init
    build_device()
  File "/home/onetwothree/.local/lib/python3.10/site-packages/keyboard/_nixkeyboard.py", line 109, in build_device
    ensure_root()
  File "/home/onetwothree/.local/lib/python3.10/site-packages/keyboard/_nixcommon.py", line 174, in ensure_root
    raise ImportError('You must be root to use this library on linux.')
ImportError: You must be root to use this library on linux.

when i’m trying to run it with sudo i’m getting this:

Traceback (most recent call last):
  File "/home/onetwothree/work/sandbox/PY/test.py", line 1, in <module>
    import pyautogui
ModuleNotFoundError: No module named 'pyautogui'

2

Answers


  1. You’ve likely installed pyautogui for your user and not root. So, the package does exist when you run Python normally, but not when you run it via sudo. Running Python with sudo will look in a different location for its packages compared to when running as a normal user.

    The easiest way to fix this would be to run pip with sudo, so it installs the package for the root user:

    sudo pip3 install pyautogui

    Login or Signup to reply.
  2. A few possible solutions here to solve your issue.

    The most obvious

    You most likely installed pyautogui using the following command.

    pip3 install pyautogui
    

    The user it’s installed under is NOT root .. You need to run:

    sudo pip3 install pyautogui
    

    That will install under root user then:

    sudo python3 test.py
    

    Should run properly.

    Alternatively

    You can use pynput which does not require root privileges to be imported.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search