pythondatetimepynput

Python - Pynput & the time module do not seem to work together in a loop


So I have written this Python script to vote repeatedly (It's allowed) for a friend on a show at a local TV station.

import os
import time
from pynput.keyboard import Key, Controller

os.system("open -a Messages")

time.sleep(3)

keyboard = Controller()

for i in range(50):
    keyboard.type("Example Message")
    print("Message typed")
    time.sleep(5)
    keyboard.press(Key.enter)
    print(f"======= {i+1} Message(s) Sent =======")
    time.sleep(40)

print("Texting Complete")

During the first loop, everything works like it's supposed to, the program takes 5 seconds between typing and pressing Enter. However, in the loops thereafter, the pynput code seems to ignore time.sleep between keyboard.type & keyboard.press, running them immediately in succession, while the print statements still respect time.sleep in the terminal output.

This isn't that big of an issue since it stills functions as intended most of the time, but about every 4th or 5th message gets sent before the program has finished typing, causing that vote not to get counted.

I'm running the script in Visual Studio Code Version: 1.99.3 on a 2021 Macbook Pro with an M1 chip, if that matters.

I have tried running the script unbuffered using the terminal, but it has made no difference.

Any help would be appreciated.


Solution

  • Solved by user @furas in the comments here, keyboard.press() keeps the button pressed, so the code needed keyboard.release() to avoid the initial keyboard.press() being held in for the rest of the loops.