Steven Lutz
Steven Lutz

Reputation: 477

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 to the screen on a specific keypress is entered, without interrupting the continuous loop running in one second intervals.

Any ideas on how to get the keypress while not distrupting the loop?

Upvotes: 3

Views: 814

Answers (2)

Praveen
Praveen

Reputation: 7222

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...

Upvotes: 1

Nir Alfasi
Nir Alfasi

Reputation: 53525

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()

Upvotes: 1

Related Questions