Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hold keys down with pynput?

Tags:

python

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')
like image 386
Clevertop Avatar asked Nov 06 '22 16:11

Clevertop


2 Answers

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) 
like image 96
BigHunger Avatar answered Nov 28 '22 02:11

BigHunger


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.

like image 38
AdityaB Avatar answered Nov 28 '22 00:11

AdityaB