Answer the question
In order to leave comments, you need to log in
How to break out of a loop when a certain word is entered?
Let's say there is a while True loop and I need to exit it by entering text or pressing keys. In this case, the loop should run until I perform the above action. How can I implement this? Linux / Ubuntu
Answer the question
In order to leave comments, you need to log in
If you want a loop that doesn't ask for input each time, you can use a non-blocking read from stdin:
while True:
try:
stdin = sys.stdin.read()
if "\n" in stdin or "\r" in stdin:
break
except IOError:
pass
time.sleep(1)
If you need a passive loop, in the spirit of "wait for input, enter exit - stop, otherwise we do something and wait again", then the solution above is suitable.
If you want an active loop that does something while the user hasn't entered anything, then input() won't work.
You can build something with threads:
1. the main thread starts the second thread, which executes the body of the loop
2. the main thread goes to input()
3. when input() exits, we send a signal to the second thread to stop and do join() to wait his.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question