1

Hi I'm trying to do something like following:

while True:
    do something 
    if key = q is been hold but not released and key = ctrl is been hold and key = shelf is been hold:
        break
    time.sleep(0.008333)#run it at 120fps

I googled around and unable to find a tool that gives you the power to check if a key has been held or not. The most is press or release? Press means the moment key from been released changed to on hold. Release means the moment key changed from on hold from released. It's a fraction of time very hard to capture. But on hold is a continuous state, it should be easy to capture.

Then I found pynput. Looks like it's also a loop. But I don't know how to run 2 loops simultaneously. One loop to do my stuff. One loop to monitor the keys then set some flag?

Or I can run the loop like this?

while True:
    do something()
    monitor key board for 0.00833333 seconds.

But I don't know how to just run pynput for just 0.0083333 seconds...

Please help?

Joyal Mathew
  • 614
  • 7
  • 24
Beterhans
  • 25
  • 1
  • 7
  • I am not sure if this is exactly what you want but there is an answer to detecting a key being held down here: https://stackoverflow.com/questions/45155643/how-would-i-implement-if-a-key-is-held-down – Joyal Mathew Oct 02 '18 at 02:35
  • 1
    Possible duplicate of [Keypress detection](https://stackoverflow.com/questions/36554353/keypress-detection) – slider Oct 02 '18 at 02:49

1 Answers1

1

Solved

I found the correct way to use pynput is to start the listener not join

and in windows Ctrl is Ctrl_l or ctrl_r shift can be shift or shift_l or shift_r on mac ctrl is ctrl

in order to be compatible I have to include all possible combinations.

import pynput,time

is_quit = False

KeyComb_Quit = [
    {pynput.keyboard.Key.ctrl, pynput.keyboard.KeyCode(char='q')},
    {pynput.keyboard.Key.ctrl_l, pynput.keyboard.KeyCode(char='q')},
    {pynput.keyboard.Key.ctrl_r, pynput.keyboard.KeyCode(char='q')}

]

def on_press(key):
    global is_quit
    if any([key in comb for comb in KeyComb_Quit]):
        current.add(key)
        if any(all(k in current for k in comb) for comb in KeyComb_Quit):
            is_quit = True

def on_release(key):
    try:
        current.remove(key)
    except KeyError:
        pass


# The currently active modifiers
current = set()

listener = pynput.keyboard.Listener(on_press=on_press, on_release=on_release)
listener.start()

##### MAIN Script #####
while True:
    do something
    time.sleep(0.00833)
    if is_quit:
        break
Beterhans
  • 25
  • 1
  • 7