Key combinations with Python from focused window only?

Is there a clean and easy way to capture key combinations with Python only when the script being run is in focus (e.g. the Python intepreter/terminal or IDE window, no global capture)?

I’ve been trying the keyboard, pynput, and pygame.key for over two months, but none of these packages worked for me and some were an incredible mess to code with IMHO due to either a lack of documentation and bugs (keyboard) or too much overhead and unwieldy, convoluted classes/methods (pygame). Assume that you need to bind 50 different hotkeys – you don’t want to define a function with 10-20 lines of code for each key binding if e.g. a simple dictionary does the job. You also don’t want to be challenged to invent some god-level regex pattern for find & replace in order to write those 50 different functions if e.g. a simple dictionary does the job. You get the point.

It’s stunning that there doesn’t seem to exist a single Python package that offers a simple, concise solution for such a banal task that virtually any program that you are using right now is getting done. Try it: Alt+F4 will close your browser, but not some other applications that you might be running in the background.

I’m thinking about something along the lines of

import keyboard_package as kb   hotkeys = {'ctrl+c':some_callback, 'ctrl+v':another_callback}    # BAM!  kb.bind_hotkeys(hotkeys)    # BAM! kb.listener_start(focus=True)    # BAM!  do_something()    # Your game main loop  kb.listener_stop()    # BAM! kb.unbind_hotkeys()    # Done! You may now go home to wife and kids. 

If it’s not possible to limit the capture on one window, I’m also fine with having the callback pause the listener, e.g. while a certain very long loop is running and you need to write an e-mail in the meantime without accidentally triggering a core meltdown by doing Ctrl+C and Ctrl+V in Outlook.

Wish list:

  • Capture hotkeys only in focused window
  • Simple, pythonic – I’m not your beta tester
  • Straight/"no BS" package that gets the job done without forcing the user do a degree on ancient Egyptian philosophy