Search code examples
pythonpython-3.xkeyboardpyautoguipynput

Pynput and pyAutoGui can't hold keys


I wanted to make a simple macro to hold down 'W' for some time, but even simple script like this does not work.

import time
import pyautogui
from pynput.keyboard import Key, Controller
keyboard = Controller()
pyautogui.keyDown('w')
time.sleep(3)
pyautogui.keyUp('w')
time.sleep(5)
keyboard.press('w')
time.sleep(3)
keyboard.release('w')

If i test it in any text editor/text input window it will write one 'w' when script starts and anouther one after 8 seconds without holding/spaming it. And therefore it DOES NOT work in any games what should be the whole purpose of this script. I tried it in a huge variety of different games (Java Minecraft, source Gmod, Roblox and some unity games) and this script just was not working in any of them, but if a game has chat, search box or any other text input window, this script will write one 'w' and anouther one after some time in it.

I realy have no idea why this is happening, but i remembered that two years ago i tried to make similar script on pynput and it did work, so i tried installing old versions of pynput, but that did not help me as well...


Solution

  • So after a long time i could finaly take care of the issue, and i figured out that the source of the problem was in the Microsoft's DirectInput. Basically pynput and pyAutoGUI are not able to get in to DirectInput and there is no signal at all while I thought that there wwas a signal, but for so little amount of time that the games just were not able to pick it up. And the solution to this was pretty easy thanks to this guy PyAutoGUI not working? Use DirectInput. Thanks to his PyDirectInput librarry you are able to use python to emulate button presses and holdes in games!