'Working on an auto clicker with python and I can't open the file

Every time I open the file through file explorer it immediately closes. I'm working on it through VS code and it runs fine through there but when I double click the file (.py) it opens the closes. I've tried making it into an exe (to give to my friend) through pyinstaller and without a -w it still closes and with a -w it says "Fatal error detected, Failed to execute script AutoClicker". I tried -w to see if the program would stay open but I assume that it closes because there is nothing to show.

import mouse
import keyboard 

while True:
    if keyboard.is_pressed(','):
        mouse.click('left')

    if keyboard.is_pressed('.'):
        break


Solution 1:[1]

You should try structuring your loop like this:

while True:
    if keyboard.is_pressed(','):
        mouse.click('left')
    elif keyboard.is_pressed('.'):
        break
    elif ...

And run your code from the terminal, if you are on Windows press Win+R, type cmd and go to the directory where your file resides (cd <directory name>). Then you can open the file with Python by typing python <filename>. If you see any errors, you should probably pip install the keyboard and mouse packages you are trying to import.

Solution 2:[2]

Try using the pyautogui (and keyboard) module, as shown below:

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

def clicky(click_key='.', stop_key='F10'):
    while not isp(stop_key):  # Execute till the stop key is pressed
        if isp(click_key):    # If click key is pressed,
            # Click the left button two times with a 0.2 second delay between clicks
            click(button='left', clicks=2, interval=0.2)
            sleep(0.5)   # Wait .5 seconds before checking again

clicky()  # Run the function

The above code works perfectly on my Windows PC. If it does not work for you, try using the pydirectinput module, it's an updated version of pyautogui (With almost the same functions - check the link). Quoting from the PyPI page:

PyAutoGUI uses Virtual Key Codes (VKs) and the deprecated mouse_event() and keybd_event() win32 functions. You may find that PyAutoGUI does not work in some applications, particularly in video games and other software that rely on DirectX. If you find yourself in that situation, give this library a try!

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 OneCricketeer
Solution 2