0

I'm trying to simulate a key being held down for a specific amount of time using python. I first tried using the keyboard module to accomplish this like so:

import time
import keyboard

keyboard.press('space')
time.sleep(5)
keyboard.release('space')

This block of code will correctly press the space key but not hold it down. It taps space and then instantly releases it before time.sleep(5) is called. The space key is pressed and released once, the program waits 5 seconds, then does nothing and exits. I also tried using the pynput module to accomplish this task like so:

import time
from pynput.keyboard import Key, Controller
keyboard = Controller()

keyboard.press(Key.space)
time.sleep(5)
keyboard.release(Key.space)

The same exact issue arises. Space is pressed and then instantly released instead of being held down. I also tried using the AHK module:

import time
from ahk import AHK
ahk = AHK()

ahk.key_down('Space')
time.sleep(5)
ahk.key_up('Space')

None of these modules have worked for me. I've tested all of them by opening up a blank notepad and then running the script.

mimky
  • 146
  • 7
  • Does this answer your question? [Python simulate keydown](https://stackoverflow.com/questions/11906925/python-simulate-keydown) – smci Feb 06 '21 at 00:44
  • That solution uses ctypes for simulating keypress. Please search all the existing questions and answers on this (search for *python simulate/simulating keypress*). There may well not be a package that does this, in which case brew your own solution using ctypes or whatever. – smci Feb 06 '21 at 00:45
  • I'm still facing the same issue where the key is pressed down once and instantly released using this method. – mimky Feb 06 '21 at 00:47
  • Have you read through the [65 hits for *python simulate keypress*](https://stackoverflow.com/search?q=python+simulate+keypress), [46 hits for *python simulating keypress*](https://stackoverflow.com/search?q=python+simulating+keypress), plus other terms... you're sure to find your answer. When you do, cite it here please. – smci Feb 06 '21 at 00:57
  • do you have the same problem with other keys? Maybe problem is keyboard (hardware), not script. – furas Feb 06 '21 at 01:40

0 Answers0