![](/img/trans.png)
[英]python exit infinite while loop with KeyboardInterrupt exception
[英]How do I exit a while loop from a keypress without using KeyboardInterrupt? [python]
我正在制作一個每隔 x 秒發出嗶聲的計時器,但在某個按鍵期間計時器會重新啟動。 代碼的第一部分讓計時器啟動。 然后它進入計時器的while循環。 我想在不按鍵盤中斷而是按另一個鍵的情況下中斷循環。
有什么幫助嗎?這是下面的代碼
import time, winsound, keyboard
x = 0
while x == 0:
if keyboard.is_pressed(','):
x = x+1
while True:
try:
while x==1:
for i in range(29):
time.sleep(1)
print(i)
if i == 28:
winsound.Beep(300,250)
except KeyboardInterrupt:
continue
這是我答應你的例子。
我不需要為此程序導入任何模塊,但我相信我用來控制鍵盤輸入的msvcrt模塊是 Windows 特定的。 是因為它可能; 盡管我們使用不同的方法來控制鍵盤輸入,但我希望您能看到在主程序反復循環和處理鍵盤輸入時如何通過按鍵來控制秒表。
import time # Contains the time.time() method.
import winsound # Handle sounds.
import msvcrt # Has Terminal Window Input methods
# ===========================================
# -------------------------------------------
# -- Kbfunc() --
# Returns ascii values for those keys that
# have values, or zero if not.
def kbfunc():
return ord(msvcrt.getch()) if msvcrt.kbhit() else 0
# -------------------------------------------
# -- Get_Duration() --
# Gets the time duration for the stopwatch.
def get_duration():
value = input("\n How long do you want the timer to run? ")
try:
value = float(value)
except:
print("\n\t** Fatal Error: **\n Float or Integer Value Expected.\n")
exit()
return value
# ===========================================
# Body
# ===========================================
# To keep the program as simple as possible, we will only use
# standard ascii characters. All special keys and non-printable
# keys will be ignored. The one exception will be the
# carriage return key, chr(13).
# Because we are not trapping special keys such as the
# function keys, many will produce output that looks like
# standard ascii characters. (The [F1] key, for example,
# shares a base character code with the simicolon.)
valid_keys = [] # Declare our valid key list.
for char in range(32,127): # Create a list of acceptable characters that
valid_keys.append(char) # the user can type on the keyboard.
valid_keys.append(13) # Include the carriage return.
# ------------------------------------------
duration = 0
duration = get_duration()
print("="*60)
print(" Stopwatch will beep every",duration,"seconds.")
print(" Press [!] to turn Stopwatch OFF.")
print(" Press [,] to turn Stopwatch ON.")
print(" Press [@] to quit program.")
print("="*60)
print("\n Type Something:")
print("\n >> ",end="",flush = True)
run_cycle = True # Run the program until user says quit.
stopwatch = True # Turn the stopwatch ON.
T0 = time.time() # Get the time the stopwatch started running.
while run_cycle == True:
# ------
if stopwatch == True and time.time()-T0 > duration: # When the duration
winsound.Beep(700,300) # is over, sound the beep and then
T0 = time.time() # reset the timer.
# -----
key = kbfunc()
if key == 0:continue # If no key was pressed, go back to start of loop.
if key in valid_keys: # If the user's key press is in our list..
if key == ord(","): # A comma means to restart the timer.
duration = get_duration() # Comment line to use old duration.
print(" >> ",end="",flush = True) # Comment line to use old duration.
t0 = time.time()
stopwatch = True
continue # Remove if you want the ',' char to be printed.
elif key == ord("!"): # An exclamation mark means to stop the timer.")
stopwatch = False
continue # Remove if you want the "!" to print.
elif key == ord("@"): # An At sign means to quit the program.
print("\n\n Program Ended at User's Request.\n ",end="")
run_cycle = False # This will cause our main loop to exit.
continue # Loop back to beginning so that the at sign
# is not printed after user said to quit.
elif key == 13: # The carriage return means to drop down to a new line.
print("\n >> ",end="",flush = True)
continue
print(chr(key),end="",flush = True) # Print the (valid) character.
# Keys that are not in our list are simply ignored.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.