pbreach
pbreach

Reputation: 16987

Leave loop early based on user input without prompting each iteration

I have a program that takes a very long time to run, and I want it to be able to do what it needs to do but then if the user hits a specific key then I want the loop to break at a certain point. Most Q&A's I have seen pertaining to this problem prompt the user to enter something on each iteration of the loop, however I do not want this. I want the loop to run undisturbed until it needs to quit.

The script will be running as an executable in a command prompt (Windows) so I guess the user could just close the window but I want the loop to break at a certain point. For example:

while True:
 print "Doing whatever I feel like"
 userinput = raw_input()
 if userinput == 'q':
    break

So this keeps printing until the user enters 'q', but it prompts the user for input each iteration. How can I avoid this?

Upvotes: 0

Views: 1281

Answers (4)

nicolas
nicolas

Reputation: 3280

Or this:

import msvcrt        
while True:
    print "Doing whatever I feel like"
    if msvcrt.kbhit():              # True if a keypress is waiting to be read.
        if msvcrt.getch()=="q":     # will not wait for Enter to be pressed
            break

Check msvcrt.

Upvotes: 1

whitebeard
whitebeard

Reputation: 1131

If you do not need to stop at a specific point, but just to be able to stop it, you could use a try/except with KeyboardInterrupt (Ctrl-C).

try:
    while True:
        print "Doing whatever I feel like"
except KeyboardInterrupt:
    exit

When the user hits CTRL-C it will exit.

Upvotes: 2

wookie919
wookie919

Reputation: 3134

Start a separate Thread to perform the computation that you need to perform while self.flag == False, and the main program can just sit there waiting for the user input. Once the user input is given, set Thread.flag = True, which will stop the Thread. Wait for the Thread to finish and join, then you can exit from the main program as well.

Upvotes: 1

Nick ODell
Nick ODell

Reputation: 25210

Two possible solutions:
1. Press Ctrl-C to close your program. This also works on linux.
2.

while True:
  for _ in range(100)
    print "Doing whatever I feel like"
  userinput = raw_input()
  if userinput == 'q':
    break

This only asks the user every 100 iterations.

Upvotes: 1

Related Questions