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!

tumultous_rooster
  • 12,150
  • 32
  • 92
  • 149
Mike Chan
  • 767
  • 2
  • 8
  • 14
  • 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. – abe Jan 30 '16 at 02: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. – bcattle Jan 30 '16 at 04:23

3 Answers3

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.

bcattle
  • 12,115
  • 6
  • 62
  • 82
1

What about

while True:
    strIn = raw_input("Enter text: ");
    if strIn == '\n':
        break;
aliasm2k
  • 883
  • 6
  • 12
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
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245