Skip to content Skip to sidebar Skip to footer

Break Loop On Keypress

I have a continuous loop that modifies data in an array and pauses for one second on every loop. Which is no problem..but I also need to have to print a specific part of the array

Solution 1:

You can use either multiprocessing or threading library in order to spawn a new process/thread that will run the continuos loop, and continue the main flow with reading the user input (print a specific part of the array to the screen etc).

Example:

import threading

def loop():
    for i in range(3):
        print "running in a loop"
        sleep(3)
    print "success"

if __name__ == '__main__':

    t = threading.Thread(target=loop)
    t.start()
    user_input = raw_input("Please enter a value:")
    print user_input
    t.join()

Solution 2:

You're probably looking for the select module. Here's a tutorial on waiting for I/O.

For the purpose of doing something on keypress, you could use something like:

import sys
from select import select

# Main loop
while True:
    # Check if something has been input. If so, exit.
    if sys.stdin in select([sys.stdin, ], [], [], 0)[0]:
        # Absorb the input
        inpt = sys.stdin.readline()
        # Do something...

Post a Comment for "Break Loop On Keypress"