Search code examples
pythonkeyboard

How do you press 2 keys at the same time with python without it alternating between them and holding them


When I try pressing 2 keys at the same time it types it fine but in a game it shows that it stops pressing one when the other one is pressed and im trying to find a way to keep both pressed the entire time until the if statement is done


import time
import keyboard
import serial

        if dataPacket.startswith(b"4"):
            keyboard.press("d")
            keyboard.press("w")  
            print ("yo1")
            time.sleep(0.1)
            keyboard.release("d")
            keyboard.release("w")
        if dataPacket.startswith(b"5"):
            keyboard.press("a")
            keyboard.press("w")   
            print ("yo2")
            time.sleep(0.1)
            keyboard.release("a")
            keyboard.release("w")
            
      


Everything except when it tries pressing 2 at once works fine and holds it but when it does try press both at a time it alternates and only presses one at a time.

Ive tryed pyautogui hotkey and that didnt work Ive tried keyboard.send("d+w", do_release=False) Ive tried keyboard.press("a, d")


Solution

  • presser.py

    import keyboard
    import time
    
    keyboard.press("d+w")
    time.sleep(5)
    keyboard.release("d+w")
    

    logger.py

    import keyboard
    import sys
    
    def on_key_event(e):
        if e.event_type == keyboard.KEY_DOWN:
            keys_pressed.add(e.name)
        elif e.event_type == keyboard.KEY_UP:
            keys_pressed.discard(e.name)
    
    keys_pressed = set()
    keyboard.hook(on_key_event)
    
    print("Press 'Esc' to exit.", end='\r')
    sys.stdout.flush()
    
    try:
        while True:
            pressed_keys = ' + '.join(keys_pressed)
            sys.stdout.write(f"\rKeys pressed: {pressed_keys: <50}")
            sys.stdout.flush()
    except KeyboardInterrupt:
        pass
    finally:
        print("\nExiting...")
    

    I've tried this and it works, if your game is not picking it up it might be that game's problem.

    GIF of it working: enter image description here