首页 > 解决方案 > 如何在不遍历整个循环的情况下检测while循环中的键盘输入

问题描述

我希望能够随时按键盘上的键,并且循环应该检测到它。现在,我必须一直按“alt”或“esc”才能让我的循环检测输入,有时它没有检测到,因为我按下的速度不够快。我只想按一次“alt”或“esc”。

我尝试在 while 循环内外使用 if 语句。我添加了尝试和除外。到目前为止,这是我的代码,它正在工作,但我必须继续按下这些按钮。


    while True:
        if keyboard.is_pressed('ctrl'):
            prg_status = True
            print("program started...")
            # goes on until it is false
            while prg_status:
                try:
                    try:
                        # "0 results matching"
                        results = browser.find_element_by_xpath("//div[@class='summary-text summary-text__expanded']").text
                    except:
                        pass
                    finally:
                        num_rslt1: int = int(results[0])

                        # if first index of the string is greater than 0, then a load is found
                        if num_rslt1 > 0:
                            # if num_rslt1 > num_rslt2:
                            #     playsound('audio.mp3')
                            # num_rslt2 = num_rslt1
                            clear_console()
                            print(results[:2], "load(s) found")
                            # playsound('audio.mp3')
                        if keyboard.is_pressed('esc'):
                            print('program terminated')
                            prg_status = False

                        if keyboard.is_pressed('alt'):
                            print('program paused')
                            time.sleep(10)

                        # click on the refresh icon every 5 sec
                        browser.find_element_by_class_name("reload-icon").click()
                        time.sleep(3)
                # if there is an error, skip so that the program keeps running instead of crashing
                except:
                    pass
        else:
            pass

我希望只按一次“alt”或“esc”,我的循环应该会检测到输入。

我一直按下按钮,有时它正在检测,有时它不是。

标签: pythonwhile-loopkeyboard-events

解决方案


推荐阅读