'How to make the key.click() repeatedly work?

I'm trying to make an autoclicker, but it's currently only clicking once when I press a random key that isn't esc.

import keyboard
import time
import pyautogui as key
time.sleep(4)
Count=0
while True:
    
    key.click()
    print('Click')
    Count=Count+1
    if keyboard.read_key()=='esc':
        print("Quit!", Count)
        break


Solution 1:[1]

The below code will keep clicking till a key (esc) is pressed:

from keyboard import is_pressed as isp
from pyautogui import click
from time import sleep

sleep(4)
count = 0
while not isp('esc'):
    click()
    print('clicky')
    count += 1
print('\nDone! Times clicked:\t', count)

If you want to do it only when a key is pressed:

from keyboard import is_pressed as isp
from pyautogui import click
from time import sleep

sleep(4)
count = 0
while not isp('esc'):
    if isp('some key'):
        click()
        print('clicky')
        count += 1
print('\nDone! Times clicked:\t', count)

Also don't EVER use while True with pyautogui, it's especially dangerous. Unless you know to trigger the failsafe, you basically can't stop if the break statement goes wrong. Take it from someone who has made that mistake.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1