Break on the keyboard
I have a continuous loop that changes data in an array and stops for one second in each loop. This is not a problem .. but I also need to print a specific part of the array to the screen when I type a specific keypress, without interrupting a continuous loop running at one second intervals.
Any ideas on how to get the keystroke without breaking the loop?
source to share
You can use multiprocessing or threading to create a new process / thread that will start the continuity loop and continue with the main thread reading 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()
source to share
You are probably looking for a module select
. Here is a guide to waiting for I / O.
To do something on the keyboard, you can 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...
source to share