Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyAutoGui - Press key for X seconds

I'm currently working on a script that presses the 'w,a,s,d' keys in order to move a character in any game. For this to work, i need to have the 'w' key pressed for a specific amount of time. How can I achieve this?

I thought of something like:

pyautogui.keyDown('w')
time.sleep(2)
pyautogui.keyUp('w')

But this just pauses the whole program and no key is being pressed so this has no use to me.

like image 825
Robin Kühn Avatar asked Feb 08 '18 09:02

Robin Kühn


People also ask

How do you press the button on pyautogui?

>>> pyautogui. press ('enter') # press the Enter key >>> pyautogui. press ('f1') # press the F1 key >>> pyautogui. press ('left') # press the left arrow key The press() function is really just a wrapper for the keyDown() and keyUp() functions, which simulate pressing a key down and then releasing it up.

How to call pyautogui functions by themselves?

These functions can be called by themselves. For example, to press the left arrow key three times while holding down the Shift key, call the following: >>> pyautogui.keyDown('shift') # hold down the shift key >>> pyautogui.press('left') # press the left arrow key >>> pyautogui.press('left') # press the left arrow key >>> pyautogui.press('left') ...

How to use pyautogui to write Hello World?

>>> pyautogui.write('Hello world!') # prints out "Hello world!" instantly >>> pyautogui.write('Hello world!', interval=0.25) # prints out "Hello world!" with a quarter second delay after each character You can only press single-character keys with write (), so you can’t press the Shift or F1 keys, for example.

How do I check if a key is valid in pyautogui?

You may also want to check out all available functions/classes of the module pyautogui , or try the search function . def type(self, *keys_or_text): '''Type text and keyboard keys. See valid keyboard keys in `Press Combination`.


2 Answers

As said in the doc-string from pyautogui.keyDown():

Performs a keyboard key press without the release. This will put that key in a held down state.

NOTE: For some reason, this does not seem to cause key repeats like would happen if a keyboard key was held down on a text field.


You need a different approach - you can may use pygame - with this

Or, if you want to stay with pyautogui you can try something like this:

def hold_W (hold_time):
    import time, pyautogui
    start = time.time()
    while time.time() - start < hold_time:
        pyautogui.press('w')
like image 164
Skandix Avatar answered Oct 21 '22 07:10

Skandix


with pyautogui.hold(key):
    pyautogui.sleep(hold)

This will do the trick without making your own function.

like image 26
OMGKewl Avatar answered Oct 21 '22 05:10

OMGKewl