Reputation: 41
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.
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
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.
Upvotes: 4
Views: 1383
Reputation: 598
You can check if a key is pressed with evdev
Check your InputDevice by looking at python -m evdev.evtest
Then to check if the s
key is pressed :
import evdev
from evdev import ecodes as e
device = evdev.InputDevice('/dev/input/event7')
if e.KEY_S in device.active_keys():
do_something()
Upvotes: 0
Reputation: 643
You will have to use the keyboard module for this, because press_key
is used to "press" the keys not to detect.
If you haven't already installed keyboard you can do it by going to 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.
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
Upvotes: 4
Reputation: 1
At first glance your problem is that you never update the value of b and it is only assigned before the loop. 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.
Upvotes: -2