簡體   English   中英

如何用特定鍵而不是鍵盤中斷異常停止無限循環?

[英]How to stop inifinite loop with specific key instead of keyboard Interrupt exception?

下面是簡化的代碼版本。 在while循環中,我通常處理來自串行端口的數據,並且測量不受時間或任何值的限制。 我想隨時停止使用鍵執行。

try-except是最簡單的方法,但它也會影響所實現的主要代碼。 就我而言,這不是一個好選擇。 我在這里找不到適合鍵盤監視的方法,在類中輸入鏈接描述 ,對於信號也是如此。 我想插入一個if語句,該語句在類中調用其他函數以停止循環執行。 任何幫助,將不勝感激。 謝謝

import time

class Something:

    def __init__(self):
        self.looping()

    def looping(self):
        i=0
        while True:
            i+=1
            time.sleep(1)
            print(i)

some=Something()
import time
class Something:
    def __init__(self):
        self.looping()

    def looping(self):
        i=0

        while True:
            try:
                i+=1
                time.sleep(1)
                print(i)
            except KeyboardInterrupt:
                break
some=Something()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM