H
H
Hachiman Hikigaya2020-12-07 02:07:14
Python
Hachiman Hikigaya, 2020-12-07 02:07:14

How to stop a script after clicking a button?

I'm using the keyboard library to run the script, but it can't be used to close the script because if you write keyboard.wait("F3") it will wait for F3 and won't go any further. I have a system:

while True:
    <...>

And if you insert keyboard.wait("F3") there, then the script will stop working until it waits for this key. I want to know how to solve this problem

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2020-12-07
@var4yn_nik

One way to solve the problem is to use multithreading. The created thread will handle keystrokes and signal this to the main one.

import keyboard
import threading
from time import sleep


def invert_event(key_event):
    if start_event.is_set():
        start_event.clear()
    else:
        start_event.set()

def listen_F3():
    # при опущении зажатой кнопки f3 
    # меняем флаг события на противоположный
    keyboard.on_release_key(key='F3', callback=invert_event)


# объект собития, с его помощью 
# сигнализируем основной поток
# о нажатии клавиши
start_event = threading.Event()
# запускаем поток обработки нажатий
threading.Thread(target=listen_F3).run()
# ждем клавишу
start_event.wait()

while start_event.is_set():
    print('processing...')
    sleep(1)

print('script finished.')

If you replace the loop condition with start_event.wait(), you can stop and resume the loop indefinitely.
while start_event.wait():
    print('processing...')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question