Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Break loop by keyboard input in python [duplicate]

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!

like image 573
Mike Chan Avatar asked Jun 23 '26 19:06

Mike Chan


1 Answers

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.

like image 154
bcattle Avatar answered Jun 26 '26 15:06

bcattle