Reputation: 151
I have a block at position (0,0). Periodically (say every 1 second) the y-coordinate of the block will randomly get updated by +/-1.
And every time the user also inputs a character (+/-) the x-coordinate will be updated by +/-1 as the user has inputted.
If it was only the x coord, I could create a while loop, that runs into the next iteration when input() gets a value.
But how can I deal with both the periodic update as well as the real time input (which can come at any time?)
Upvotes: 0
Views: 136
Reputation: 5176
Threading is your friend:
import time
from threading import Thread
# This defines the thread that handles console input
class UserInputThread(Thread):
def __init__ (self):
Thread.__init__(self)
# Process user input here:
def run(self):
while True:
text = input("input: ")
print("You said", text)
# Exit the thread
if text == "exit":
return
console_thread = UserInputThread()
console_thread.start()
while True:
time.sleep(5)
print("function")
# If the thread is dead, the programme will exit when the current iteration of the while loop ends.
if not console_thread.is_alive():
break
UserInputThread
runs in the background and handles the user input. print("function")
could be any logic you need to do in the main thread.
Upvotes: 1