3

I am making a script that remaps a single key (right-ctrl) into alt+tab using the Python library known as keyboard. This was easy to do with Autohotkey on windows, however, this doesn't seem to be possible on Linux. After all in the keyboard documentation they have funcion(param, param, Suppress=False), so it should work right?

import keyboard

def altTab:
    keyboard.release(97)
    keyboard.send("alt+tab")

# 97 is the key_code for [right ctrl] on my system
keyboard.on_press_key(97, altTab, suppress=True)

 
I've tried releasing the key from the code standpoint but it doesn't seem to work, as ctrl+alt+tab is different from alt+tab. I have also tried using the keyboard.remap_key function to change right ctrl into right alt, and right alt into left alt so that right alt would work, then sending just tab instead of alt+tab but it still doesn't work. I am using Ubuntu Linux.
Please help, I'm stumped

Glory to Russia
  • 17,289
  • 56
  • 182
  • 325
255.tar.xz
  • 700
  • 7
  • 23

1 Answers1

3

You need hook_key, that is the method to call provided callback every time provided key is pressed:

import keyboard

def altTab(e):
    if e.event_type == "down":
        keyboard.release(97)
        keyboard.send("alt+tab")

# 97 is the key_code for [right ctrl] on my system
keyboard.hook_key(97, altTab, suppress=True)

Edit: added code to deal with key press only.

ipaleka
  • 3,745
  • 2
  • 13
  • 33
  • while this does work, it is basically the same thing as doing `keyboard.on_release_key` which is not what I want, I need `keyboard.on_press_key`, so thanks, but this isn't quite what I was looking for – 255.tar.xz Jul 02 '19 at 01:50
  • this answer also doesn't work for me because it triggers both on press (but doesn't work obviously) and on release (which is not what I want) – 255.tar.xz Jul 02 '19 at 01:53
  • [Docs](https://github.com/boppreh/keyboard/blob/master/README.md#keyboardhook_keykey-callback-suppressfalse) says it handles both. test and change the altTab method for your needs. – ipaleka Jul 02 '19 at 02:00
  • Still doesn't work bro, this is a sloppier (not to be rude or anything) version of `keyboard.on_press_key` (which is not a single time thing like you have said) – 255.tar.xz Jul 03 '19 at 19:25
  • I've looked into `pynput`, however, it requires an active `X server`... I am trying to achieve this *Without* using an `x server` – 255.tar.xz Jul 29 '19 at 15:22