Cassiterite
Cassiterite

Reputation: 45

Python: Toggle a while loop with the same hotkey without exiting the code

I am trying create something like a "spam bot" (for educational purpose). I want it something like this: When I press a key on my keyboard (e.g.: f1), the function (while loop) should keep looping and stop only when I press the same key again (In this example: f1). Here's a code I made...

import pyautogui
from pynput import keyboard
import time
import threading

text = pyautogui.prompt('Text: ')
def text():
    while running:
        pyautogui.press('enter')
        pyautogui.write(text)
        pyautogui.press('enter')
        time.sleep(3)

def on_press(key):
    global running
    if key == keyboard.Key.f1:
        running = True
        t = threading.Thread(target=text)
        t.start()
    if key == keyboard.Key.f2:
        return False

def on_release(key):
    global running
    if key == keyboard.Key.f2:
        running = False
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

However, this code uses 2 different keys to start/stop (f1 & f2) and it exits the program when I press f2. Is it possible to use only 1 key to toggle start/stop? Also, I don't want to exit the program when I press the "stop" key, I want it to keep running (being able to start/stop the loop whenever I want without exiting).

Upvotes: 1

Views: 1749

Answers (1)

quamrana
quamrana

Reputation: 39404

You should use your running variable as a simple state machine with just two states:

running = False

def on_press(key):
    global running
    if key == keyboard.Key.f1:
        running ^= True
        if running:
            t = threading.Thread(target=text)
            t.start()

Upvotes: 2

Related Questions