Search code examples
pythonpython-2.7windows-7interruptpause

Python, How to stop a script midway?


Let's say I have this script:

import time

def menu():
    n = raw_input("What do you want the script to do: ").lower()
    if n == "run":
        r = run()
    elif n == "exit":
        exit()
    else:
        print("Unknown command")
    print("Result: " + r)    

def run():
    t = 0
    while t < 60:
        print("This script is doing some stuff")
        time.sleep(1)
        t = t + 1
    return "Some kind of result"

if __name__ == '__main__':
    print("Starting the most useless script ever")
    while True:
        menu()

How can I stop the script while printing "This script is doing some stuff" and return to Menu()? I dont want to totally exit the program, just to return to menu.


Solution

  • What about something along this:

    while True:
        try:
            # whatever logic
            pass 
        except(KeyboardInterrupt):
            print 'Ctrl-C was pressed... interupt while loop.'
            break
    print 'program still running'