0

I want to build a program that moves a mouse in a square and have a delay between each action so it doesn't go crazy.

The only way I know of right now is time.sleep(). The only problem is that I want to terminate the program with a keypress but, while the program sleeps, it doesn't take in any input. So the key must be pressed down as long as it takes for the next loop iteration to be registered. My goal is to terminate it at any (even when sleeping) moment. The only way I could imagine fixing it would be to make my program multi-threaded and ending the thread via a separate thread or "master thread" by killing the working one.

Please let me know what you think.

Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
  • There are plenty of ways to wait for input _without_ using `time.sleep()`. At the OS level, the operating system has blocking syscalls, like `select()`, that can wait until there's input ready (or a timeout is reached) before returning, thus sleeping exactly as long as necessary and no longer. At higher levels, most of your GUI frameworks support an "event loop" that behaves similarly, blocking until there's an event ready to process (typically using `select()` or `poll()` under the hood to wait until the file descriptor used to connect to the GUI framework has content ready to consume). – Charles Duffy Feb 13 '22 at 22:10
  • ...so the linked duplicate is a _literal_ duplicate (it answers exactly what you asked), but it also probably isn't what you want to use to solve your immediate problem (because the best approach doesn't use `time.sleep()` at all). The right thing to use to solve your problem depends on the specific GUI framework you're using; read its documentation -- they all have some means or another to address this issue. – Charles Duffy Feb 13 '22 at 22:13

0 Answers0