user16912887
user16912887

Reputation:

Can a for loop be timed?

from ast import Break
import pyautogui as pat
import pyautogui
import time
import keyboard

# time.sleep(3)

# print(pat.position())

    pat.click(x=712, y=1052, duration=1)
    pat.click(x=1108, y=917)
    
    file = open('peanut.txt', 'r').readlines()
    
    for i in file:
        pat.typewrite(i, interval=0.1)
        pat.press('enter') 

How do I time the for loop to stop or command the loop to stop by pressing a key?

I tried using the keyboard module but I could only find a simulation of the 'esc' key but I cannot seem to figure out what module would allow me to physically press a key to quit the program?? Any help would be fantastic. Thank you!

Upvotes: 0

Views: 57

Answers (1)

fourseven
fourseven

Reputation: 11

you can bind any key to stop loop

import keyboard
number=1
while True:
    number=number+1
    print(number)
    keyboard.wait("escape")

try this code this code will print a number and will wait escape, if escape is pressed will print another number infinitely or you can do this

import keyboard
number=1
while True:
    number=number+1
    print(number)
    if keyboard.is_pressed("escape"):
        break
    else:
        pass
def AfterLoopWhile(): 
    """This code can't execute if the loop isn't break (Sorry for my 
    english)"""
    print("Stopped the loop")
AfterLoopWhile() "If the loop is break, execute the function AfterLoopWhile

to stop the loop or you can quit if escape is pressed

import keyboard
number=1
while True:
    number=number+1
    print(number)
    if keyboard.is_pressed("escape"):
        exit()
    else:
        pass

Upvotes: 1

Related Questions