Search code examples
pythonpython-multithreadingpynput

Simulating key hold without stopping loop


I'm using pynput to simulate key press.

Here's my function i'm using in a loop

def press_hotkey(key, time):
    keyboard.press(key)
    sleep(time) #hold time
    keyboard.release(key)

Sometimes I need to press one key for certain amount of time, for example 2 seconds, but I don't want to stop my loop, as it should continue and press next key if needed.

What would be the most correct way to do that? Is running a function in new thread every iteration a good idea?


Solution

  • you could use threading module

    import threading
    

    and then call your function within the thread like this

    thread = threading.Thread(target=press_hotkey, args=(desired_key, desired_time))
    thread.start()