【问题标题】:Looping until a specific key is pressed [duplicate]循环直到按下特定键[重复]
【发布时间】:2022-12-31 04:43:20
【问题描述】:

我试图制作一个 while 循环,它会在按下特定键时停止运行。问题是循环无限运行。我的循环:

import time
import keyboard

while (not keyboard.is_pressed("esc")):
    print("in loop...")
    time.sleep(2)

我正在使用 keyboard 模块。我的循环有什么问题,我该如何解决? (在这种情况下,我真的不想使用 Repeat-until or equivalent loop in Python 东西。)

【问题讨论】:

  • 嗨,这在 ubuntu 20.04 上运行良好
  • @Stubborn 好的,所以我测试了它。它有效但不是我想要的。它仅在您完美计时时(从循环的最后一行到第一行的时刻)检测到压力机。 import keyboard import time while (not keyboard.is_pressed("esc")): print("in the loop") time.sleep(2) print("out of the loop")你可以明白我的意思了^
  • 它在 Windows 10 上运行良好
  • @FrancisKing 在测试之后,我发现它可以工作,但不是我想要的那样工作(尝试使用上面的代码)。您只能在特定时刻跳出循环——并非总是如此。我想要实现的是创建一个循环,无论其完成状态如何,它总是会中断(您可以随时中断)。

标签: python python-keyboard


【解决方案1】:

这是一个有效的解决方案:

import keyboard
import time
import threading

class main:
    def __init__(self):
        # Create a run variable
        self.run = True

        # Start main thread and the break thread
        self.mainThread = threading.Thread(target=self.main)
        self.breakThread = threading.Thread(target=self.breakThread)

        self.mainThread.start()
        self.breakThread.start()

    def breakThread(self):
        print('Break thread runs')
        # Check if run = True
        while True and self.run == True:
            if keyboard.is_pressed('esc'):
                self.newFunction()

    def main(self):
        print('Main thread runs')
        
        # Also check if run = True   
        while not keyboard.is_pressed('esc') and self.run:
            print('test')
            time.sleep(2)
            
            # Break like this
            if keyboard.is_pressed('esc'):
                break

            print('test')
            time.sleep(2)

    def newFunction(self):
        self.run = False
        print('You are in the new function!')

program = main()

【讨论】:

  • while True and self.run == True只是while self.run...
【解决方案2】:

你不需要 while 循环中的括号,这是我的代码:

import keyboard

# You need no brackets
while not keyboard.is_pressed('esc'):
    print('test')

【讨论】:

  • 它工作正常,因为循环内没有太多与等待相关的代码。但是,如果我想添加一些等待(请参阅上面的评论),您会看到它只会在特定时间中断(我希望我的循环中断而不管循环的完成状态如何)。
  • 如果你在循环中有停顿,只要你有停顿,你就必须按下键,除非你准确地抓住了循环结束的点。只有在循环从头开始时才会询问是否按下了键。我希望这会有所帮助 :)。
  • 有什么方法(比如创建多个线程)可以实现我想要的吗?方法是否有效?
  • 如果使用 if 按下键,您可以在 while 循环中多次查询,否则它也应该适用于线程。但我必须先测试一下。
  • 括号不是必需的,但它们也不会改变任何东西。它们肯定不是任何问题的原因,并且由于您已经发布了另一个答案,请删除这个...
猜你喜欢
  • 2021-05-17
  • 2015-09-23
  • 1970-01-01
  • 2021-11-12
  • 2017-07-03
  • 2014-09-12
  • 1970-01-01
  • 2011-12-28
  • 2019-06-13
相关资源
最近更新 更多