I had this issue on my PC (running mint), I assume it's the same on a Pi running Raspbian or whatever.
As per this: https://stackabuse.com/guide-to-pythons-keyboard-module/ you need to install the keyboard module as root. So sudo pip3 install keyboard, and then run the python script with sudo.
That seems to work.
I know that this question is from 4 years ago but I found it in my searches so I am going to put what helped me after I found this dead question.
I used this little wrapper: https://gist.github.com/sloria/5693955
# -*- coding: utf-8 -*-
Provides WAV recording functionality via two approaches:
Blocking mode (record for a set duration):
I have a pi4 that is behaving exactly like what you described after upgrading from 20.04 to Ubunth 21.04 (logitech wifi keyboard + mouse pad combo).
Below solution from https://www.raspberrypi.org/forums/viewtopic.php?t=310293#p1889485 worked for me.
find a physical keyboard
"at the gdm3 login screen use the gear icon at bottom right ...