I'm writing a python application for Raspberry Pi that should be able to respond to keyboard shortcuts. I've made a few attempts at using alternative solutions, but in the end the only thing that appears to have worked well in context is keyboard (https://pypi.org/project/keyboard/).
The keyboard library requires root on Linux-based systems. Installing keyboard as root (eg. 'sudo pip3 install keyboard') is easy enough, as is running the python program making use of keyboard as root. However, keyboard isn't the only third-party library I'll be using, and those weren't installed as root in the first place. So when I run my application as root, it can only import keyboard, whilst if I don't run it as root, it can import everything except keyboard.
Do I need to reinstall all the other libraries as root to get them working alongside keyboard, or is there anything else I can do to make the non-root installed libraries accessible when running my application as root in order to use keyboard?
Whenever possible, it's preferable to install libraries as a non-root user. I'm not familiar with the keyboard package, but perhaps it only requires the user to be in a specific group. I would guess that you only need the user to be in the input
group (or whichever group owns the devices in /dev/input.) If possible, I would try adding the user to the input group:
sudo usermod -aG input USER
Be sure to log out and log back in as that user, because that user won't be added to the group until a new session is started.
If you actually need to run as root, you have a couple of options...
You can either install all of the libraries as root, or you can add to the python path when you run the executable. This can be done using the PYTHONPATH environment variable.
PYTHONPATH
Augment the default search path for module files. The format is the same as the shell’s PATH: one or more directory pathnames separated by os.pathsep (e.g. colons on Unix or semicolons on Windows). Non-existent directories are silently ignored.
In addition to normal directories, individual PYTHONPATH entries may refer to zipfiles containing pure Python modules (in either source or compiled form). Extension modules cannot be imported from zipfiles.
The default search path is installation dependent, but generally begins with prefix/lib/pythonversion (see PYTHONHOME above). It is always appended to PYTHONPATH.
An additional directory will be inserted in the search path in front of PYTHONPATH as described above under Interface options. The search path can be manipulated from within a Python program as the variable sys.path.
You can simply set PYTHONPATH when you run the executable.
PYTHONPATH=/PATH/TO/USER/LIBRARIES /path/to/application