2

I have a problem with breaking out of a loop by pressing a key.

I googled around and found msvcrt module but it did not solve my problem.

Here is my code.

while True:
    """some code"""
    if *keyboard_input: space* == True:
        break

I know it's a easy question but I just can't find the right module to import.

Thanks!

2
  • A continuous loop? Or one that will prompt the user and allow an option such as "quit?" You cannot stop a continuous loop with a keyboard interrupt without the interrupt killing the whole program. Commented Jan 30, 2016 at 2:59
  • 1
    This is marked as a duplicate of a question that has nothing to do with breaking out of a loop. This is not a duplicate. Commented Jan 30, 2016 at 4:23

3 Answers 3

8

Use a try/except that intercepts KeyboardInterrupt:

while True:
    try:
        # some code
    except KeyboardInterrupt:
        print 'All done'
        # If you actually want the program to exit
        raise

Now you can break out of the loop using CTRL-C. If you want the program to keep running, don't include the raise statement on the final line.

Sign up to request clarification or add additional context in comments.

Comments

1

What about

while True:
    strIn = raw_input("Enter text: ");
    if strIn == '\n':
        break;

Comments

0

This loop will run continuously (and print what you type) until you type enter or space+enter.

Basically, you won't be able to break directly on a space.

while True:
    s = raw_input(">>")
    if len(s) <= 1:
        break
    print s

1 Comment

I think you meant if len(s) >= 1: break

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.