I'm using pynput and I would like to be able to hold keys down, specifically wasd but when I try and run this code it only presses the key and doesn't hold it for 2 seconds. If anyone knows what I'm doing wrong let me know. Thanks
import time
keyboard = Controller()
time.sleep(2)
keyboard.press('w')
time.sleep(2)
keyboard.release('w')
Try to hold your keys by using the "with" statement. In my example it holds "alt" and tabs around.
import time
from pynput.keyboard import Key, Controller
keyboard = Controller()
with keyboard.pressed(Key.alt):
keyboard.press(Key.tab)
time.sleep(1)
keyboard.press(Key.tab)
time.sleep(1)
keyboard.press(Key.tab)
time.sleep(1)
Maybe try PyAutoGui. It is easier, and can be used within a few lines of code. I got the code from here
>>> import pyautogui
>>> screenWidth, screenHeight = pyautogui.size()
>>> currentMouseX, currentMouseY = pyautogui.position()
>>> pyautogui.moveTo(100, 150)
>>> pyautogui.click()
>>> pyautogui.moveRel(None, 10) # move mouse 10 pixels down
>>> pyautogui.doubleClick()
>>> pyautogui.moveTo(500, 500, duration=2, tween=pyautogui.easeInOutQuad) # use tweening/easing function to move mouse over 2 seconds.
>>> pyautogui.typewrite('Hello world!', interval=0.25) # type with quarter-second pause in between each key
>>> pyautogui.press('esc')
>>> pyautogui.keyDown('shift')
>>> pyautogui.press(['left', 'left', 'left', 'left', 'left', 'left'])
>>> pyautogui.keyUp('shift')
>>> pyautogui.hotkey('ctrl', 'c')
If you want to just press a key down then do
from pyautogui import*
from time import sleep
keyDown("a") #pressing down key 'a'
sleep() #how ever long you want
keyUp("a") #stop pressing key 'a' down
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With