I used the keyboard python library to get keyboard inputs into my application and I found a strange irregularity. When testing on Windows, the print result shows capital or lower case letters based on whether or not I'm holding down the shift key. However when testing on Debian linux, it seems to only report lower cases regardless if I am holding down shift or not. As the matter of fact this also affects punctuation symbols, special characters and brackets. Shift 5 still shows up as 5 Is this something that's unavoidable or is there something I'm missing?
I'd like the library to provide me with capitals and special characters on linux, like it does on windows, because otherwise I'm gonna have to do my own lookup table to conversion.
import keyboard
while True:
event = keyboard.read_event()
if event.event_type == keyboard.KEY_DOWN:
print(dir(event))
print('key pressed', event.name)
Ok, I still don't understand which you want to do (make keys uppercase or lowercase), so here's an example of both.
Lowercase ALWAYS:
from pynput.keyboard import Listener
def on_press(key):
try:
print(key.char)
except:
print(key)
with Listener(on_press=on_press) as listener:
listener.join()
And for always uppercase:
import keyboard
hotkeys = []
nums = {1: '!', 2: '@', 3: '#', 4: '$', 5: '%', 6: '^', 7: '&', 8: '*', 9: '(', 10: ')'}
letters = 'abcdefghijklmnopqrstuvwxyz'
for letter in letters:
hotkeys.append(letter)
for num in range(10):
hotkeys.append(str(num))
while True:
for hotkey in hotkeys:
if keyboard.is_pressed(f'shift+{hotkey}'):
try:
hotkey = int(hotkey)
print(nums[hotkey])
except:
hotkey = hotkey.upper()
print(hotkey)
while True:
if not keyboard.is_pressed(f'shift+{hotkey}'):
break
elif keyboard.is_pressed(hotkey):
print(hotkey)
while True:
if not keyboard.is_pressed(hotkey):
break
The lowercase code works by using pynput
, which gives lowercase letters no matter what, and is arguably a better python library than keyboard
.
The uppercase code is a little more complicated. I made a list of some hotkeys that are possible, like 'shift+5' is '%', then I go into a while True loop and wait for a key to be pressed. First we check if the user also pressed shift, and if they didn't press shift, then we just print the hotkey in the lowercase version. This code obviously doesn't cover every character (like '|'), but it does cover the most used ones. You could add more to your liking.
Also note that I added a while loop so keyboard input isn't echoed (detects multiple times after only one key stroke), so you must release the key before the next iteration of the loop starts.