1

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.

Programer Beginner
  • 1,377
  • 6
  • 21
  • 47

2 Answers2

1

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'
Julien
  • 13,986
  • 5
  • 29
  • 53
0

What you're looking for is the signal library, all you'll need to do is create a function to handle it.

import signal

def a(sig_num, stack_frame):
    print("WORKS")

signal.signal(signal.SIGINT,a)

The function a has to have two positional arguments

Andria
  • 4,712
  • 2
  • 22
  • 38