0

I'm trying to set up a python program that allows me to type in the terminal and have a basic caesar shift printed out - I type 'a', it prints 'n', I press 'b' it prints 'o'.

The most recommended package for this, really the only recommended one, is not fully supported for mac, but mostly works (package: https://github.com/boppreh/keyboard/).

I set up a minimal example, run with sudo (to allow terminal to monitor this, and after granting terminal accessibility control via system preferences), and get a weird result:

I click in terminal and press 'a', the 'a' I typed appears, but nothing else I click elsewhere (e.g. on a browser, chaning the focus), press 'a', the program picks that up and lets me know

code:

import keyboard
from time import sleep


def log_move(char):
    print(f"keypress of {char}")


keyboard.on_press_key("a", lambda _: log_move("a"))
while True:
    sleep(1)

input: type 'a' while terminal in focus

output: letter 'a' typed, no code activation

expected output: letter 'a' typed (potentially), code outputs 'keypress of a'

input: type 'a' while terminal not in focus

output: code outputs 'keypress of a'

expected output: code outputs 'keypress of a'

I would expect if anything that the terminal would fail to pick up inputs when not in focus but would get them when in focus (I don't actually need inputs when terminal out of focus)

Possibly related (unsolved and has a concrete error but no report of it partially working like mine does): python keyboard does not recognize keys

  • https://pypi.org/project/keyboard/ the very first line: "captures keys **regardless of focus**" – Random Davis Nov 18 '22 at 17:23
  • while the terminal is in focus, the library cannot capture keys. Changing the focus to something else then allows it to capture keys. Changing back to have terminal in focus blocks capture again. This is therefore counter to documentation – Linen Soup Nov 18 '22 at 17:25
  • I suggest seeing if your issue is on the official issues page https://github.com/boppreh/keyboard/issues but the fact that you said that this is not fully supported on mac makes me think that you might have success if you try another library which is fully supported. – Random Davis Nov 18 '22 at 17:27
  • it is not listed. Are you aware of any other libraries with similar functionality? I have found none. – Linen Soup Nov 18 '22 at 17:31
  • There's others, like pynput. Here's a post about it, explaining how the process has to be run as root in order to work, as there's a security feature in OS X that might be blocking some of the functionality. Maybe that's related to the issue here, too. https://stackoverflow.com/a/47519904/6273251 – Random Davis Nov 18 '22 at 17:33

0 Answers0