简体   繁体   中英

Python3 toggle script on key press stuck

The goal of this script is to make a switch and let the user toggle it ON and OFF with a key press, and when the switch is ON, the script should execute a loop that print a message in the terminal. In another words, The goal is to repeatedly print a message when the switch is ON

Here is what i have tried:

import keyboard
import time

switch = 0    # The switch variable


def check_start():
    global start
    if keyboard.is_pressed("F5") and start == 0:    # If F5 is pressed, turn ON print message loop
        switch = 1
        print(switch)
        time.sleep(0.1)    # This is to prevent the user toggling the switch too fast

    if keyboard.is_pressed("F5") and start == 1:     # If F5 is pressed again, turn OFF print message loop
        switch = 0
        print(switch)
        time.sleep(0.1)


def print_name():    # If the switch is ON, it should print two seperate message with a 10 seconds interval
    if start == 1:
        print("start")
        time.sleep(10)
        print("end")


while True:
    check_start()
    print_name()

Here is the output of the script:

1
start
end
start
end
0
1
start
end
0

Now here's the problem:

The user cannot turn off the switch while the print loop is in progress. For example the user cannot turn off the script if the message "end" has not printed, the user can ONLY turn off the switch exactly after "end" has printed, and if the user has missed the opportunity to turn off the switch, he must wait 10 more seconds to turn it off. What i expected is the user can toggle On and OFF anytime s/he wishes to.

Is this possible to do in without importing too much module?

you can put an if condition inside your loop to do a break at a specific key

ex:

if keyboard.is_pressed("F5") and start == 1:
    break

this would exit your infinite loop, although a more elegant code would work like this:

def check_start():
    global start
    if keyboard.is_pressed("F5") and start == 0:
        #DO stuff
        return True

    if keyboard.is_pressed("F5") and start == 1:
        #DO stuff
        return False


while check_start():
    print_name()

Here is a cleaner, more reliable approach using keyboard's built-in add_hotkey method.

Below is a simple program to toggle printing of the current timestamp.

import keyboard as kb
from datetime import datetime as dt

global print_flag
print_flag = False

def toggle_print():
    global print_flag
    print_flag = not print_flag

kb.add_hotkey('d', toggle_print)

while True:
    timestamp = dt.now()
    if print_flag:
        print(timestamp)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM