[英]Python3 toggle script on key press stuck
該腳本的目標是制作一個開關,讓用戶通過按鍵將其打開和關閉,當開關打開時,腳本應執行一個循環,在終端中打印一條消息。 換句話說,目標是在開關打開時重復打印一條消息
這是我嘗試過的:
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()
這是腳本的 output:
1
start
end
start
end
0
1
start
end
0
現在問題來了:
當打印循環正在進行時,用戶不能關閉開關。 例如,如果消息“end”還沒有打印,用戶不能關閉腳本,用戶只能在“end”打印完后關閉開關,如果用戶錯過了關閉開關的機會,他必須再等 10 秒才能將其關閉。 我所期望的是用戶可以在他/她希望的任何時候打開和關閉。
這可以在不導入太多模塊的情況下完成嗎?
您可以在循環中放置一個 if 條件以在特定鍵處中斷
前任:
if keyboard.is_pressed("F5") and start == 1:
break
這將退出您的無限循環,盡管更優雅的代碼會像這樣工作:
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()
這是使用鍵盤內置的 add_hotkey 方法的更簡潔、更可靠的方法。
下面是一個簡單的程序來切換當前時間戳的打印。
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.