简体   繁体   English

当使用 Autokey 按下某个键时,如何停止 while 循环?

[英]How do I stop a while loop when a key is pressed with Autokey?

I'm trying to write a small script with Autokey (not regular Python) on Linux Mint which presses a single key and stops after I press another specific key but I can't get it to stop the loop after I press this specific key.我正在尝试在 Linux Mint 上使用Autokey (不是常规 Python)编写一个小脚本,它按下一个键并在我按下另一个特定键后停止,但在我按下这个特定键后我无法让它停止循环。

I got the loop working but I can't make it stop.我让循环正常工作,但我无法让它停止。

import time
a = True
b = keyboard.press_key('s')
keyboard.release_key('s')
while a:
    keyboard.send_key("a", repeat=5)
    time.sleep(2)
    if b:
        break

So this outputs the letter "a" indefinitely and after I press "s" it doesn't stop and I don't know what I'm doing wrong所以这会无限期地输出字母“a”,在我按下“s”后它不会停止,我不知道我做错了什么

I read about the while function and break but all the examples I found were with a loop stopping after it reached a certain number and these examples with numbers are different than what I try to achieve with this kind of script so I hope someone can help me to figure this out.我阅读了 while 函数和 break 但我发现的所有示例都在达到某个数字后循环停止,这些带有数字的示例与我尝试使用此类脚本实现的不同,所以我希望有人可以帮助我弄清楚这一点。

You will have to use the keyboard module for this, because press_key is used to "press" the keys not to detect.为此,您将不得不使用键盘模块,因为press_key用于“按下”不被检测的键。

If you haven't already installed keyboard you can do it by going to cmd, pip install keyboard如果你还没有安装键盘,你可以通过 cmd, pip install keyboard

after that you can add the code in python as follows, pressing "q" will print "a" 5 times and pressing "s" will stop the program.之后你可以在python中添加如下代码,按“q”将打印“a”5次,按“s”将停止程序。

import keyboard
while True: 
   if keyboard.is_pressed('q'):  # pressing q will print a 5 times
      for i in range(5):
         print("a")
      break  
   elif keyboard.is_pressed('s'): # pressing s will stop the program
      break

You can check if a key is pressed with evdev您可以使用evdev检查是否按下了某个键

Check your InputDevice by looking at python -m evdev.evtest通过查看python -m evdev.evtest检查您的 InputDevice

Then to check if the s key is pressed :然后检查是否按下了s键:

import evdev
from evdev import ecodes as e

device = evdev.InputDevice('/dev/input/event7')

if e.KEY_S in device.active_keys():
    do_something()

At first glance your problem is that you never update the value of b and it is only assigned before the loop.乍一看,您的问题是您从不更新 b 的值,它仅在循环之前分配。 You should probably try something like this:你可能应该尝试这样的事情:

import time
a = True
keyboard.release_key('s')
while a:
    keyboard.send_key("a", repeat=5)
    b = keyboard.press_key('s')
    time.sleep(2)
    if b:
        break

I don't know how "b = keyboard.press_key('s')" affects the code, if it stops it.我不知道“b = keyboard.press_key('s')”如何影响代码,如果它停止它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM