How to get out of a while loop with a specific key

Question:

I am trying to make an auto clicker but when i try to make my code exit it doesnt
here is my code

import mouse
import keyboard
import time
import os
os.system('cls')
def Config():
    print("Click every")
    hour = int(input("Hour: "))
    minute = int(input("Minute: "))
    second = int(input("Second: "))
    total_time = hour*3600 + minute*60 + second
  
    print("f6 to start and f10 to stop")
    keyboard.wait('f6')
    while True:
        time.sleep(total_time)
        mouse.click()
            
            

#def Fastest():

print("    Auto clicker!!!")
print("       By ze")
print("-------------------------")
print("Auto click on desired time or Fastest?")
choose = int(input("""
1. Config (No milliseconds)
2. Fastest
"""))
if choose == 1:
    Config()
# elif choose == 2:
#     Fastest()

#TODO:
# use mouse.click
# make it click with time
# make function fastest start with f1 and stops with f2
# create back up file

i tried an if statement with keyboard.is_pressed(‘key’) thinking it would work but it doesnt my results are that the code exits (if key is pressed then exit)

Asked By: Zezoman

||

Answers:

You need to check if the key is pressed in your infinite loop. If it is pressed, you need to exit

while True:
    time.sleep(total_time)
    mouse.click()
    if keyboard.is_pressed("f10"):
        break

But this waits for the sleep function , so you’ll need to hold f10 for total_time seconds.


You should use a loop to check for the key, rather than sleeping

import datetime

...
clicking = True
while clicking:
    mouse.click()

    s = datetime.datetime.now()

    while ((datetime.datetime.now()-s).total_seconds() < total_time):
        # This runs while the difference in time since you started the loop is less than the time you want to wait
        if keyboard.is_pressed("f10"):
            clicking = False
            break
Answered By: Freddy Mcloughlan

Use one thread to handle user input and another thread to do the clicking:

from threading import Thread
from msvcrt import getwch
import mouse

done = False
def auto_click():
    print("Press "q" to quit")
    global done
    while True:
        if getwch() == "q":
            done = True
            break
Thread( target = auto_click, daemon = True ).start()

while not done: # you can add whatever logic you want including a time gate here
    mouse.click()
Answered By: Carter Canedy
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.