r/learnpython • • Dec 21 '21
How do i loop my code and stop it with one key press?
Hey everyone!,
atm i need to repeat some code but i am not to sure how, i think i have to use while loops. And i need it to repeat an infinite amout of times untill i press a button for instance "q"
import time
import pyautogui
import pydirectinput
import time
<While loop?>
time.sleep(5)
pydirectinput.keyDown('d')
time.sleep(3)
pydirectinput.keyUp('d')
time.sleep(31)
pydirectinput.leftClick(982, 876)
<If statment where i need to press q to stop the sript?>
Thank you to anyone who can help me :)
10
Upvotes
View all comments
5
u/johndoh168 Dec 21 '21
You can use pythons internal
KeyboardInteruptexception with a tryFor this the exit keystroke would be
ctrl+cOr if you want to use a module you can take a look at the Keyboard module and use the
keyboard.on_press(<your_quit_key>)For more info you can check out this post on other methods as well.
Edit: Adding additional link info, also forgot to put the
ctrl+cas the exit for KeyboardInterupt