Python - A keyboard command to stop infinite loop?

PhillipKregg picture PhillipKregg · Dec 1, 2011 · Viewed 166.1k times · Source

Possible Duplicate:
Why can't I handle a KeyboardInterrupt in python?

I was playing around with some Python code and created an infinite loop:

y = 0
x = -4

itersLeft = x
while(itersLeft<0):
    y = y + x
    itersLeft = itersLeft - 1
    print "y = ",y, "itersLeft = ", itersLeft

print y

Is there a keyboard shortcut that would allow me to stop the looping - allowing me to fix the loop and then restart it?

I've tried Ctrl+C and didn't have any luck. If it helps I'm using a Windows 7 environment.

Thanks.

EDIT


I should have also mentioned that I'm using Aptana Studio 3 and attempted to run the Ctrl+C command within that. It doesn't work there - but trying it within the regular console works fine. I'm assuming it must be because of the Aptana environment.

Answer

kindall picture kindall · Dec 1, 2011

Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.

Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.