21

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.

4
  • That should do it. What did you use to run it? Commented Dec 1, 2011 at 0:48
  • 1
    Seeing that you are using Aptana Studio 3, is it at least 3.03? jira.appcelerator.org/browse/APSTUD-1469 What happened when you killed it with task manager? Have you tried ctrl+z? Commented Dec 1, 2011 at 0:55
  • press the red stop button on the eclipseIDE Commented Dec 1, 2011 at 1:02
  • 2
    Why the hell is this marked as a duplicate? That's just plain dumb, excluding cursing. The so-called "original" is about catching KeyboardInterrupt errors. Commented Jun 22, 2014 at 19:27

1 Answer 1

33

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks Kindall. I should also have mentioned that I'm using Aptana Studio 3 and attempted to use the Ctrl-C command there. It works fine in the regular terminal window, but not within Aptana. I actually had to restart Aptana in order to stop the loop.
@Phillip: Don't know about Aptana, but most IDE's have a "Stop" or "Stop and Restart" button for console apps.
Ok, thanks for the help - I was just hoping the keyboard shortcut would work within Aptana.
what if you executed the python script from rc.local? :(
I've got nothing but an anecdotal "hunch" but I feel runaway printing responds more snappily to <C-c> when the -u command line flag (for unbuffering stdout/err) is set. Eg. python -u my-loop-script.py.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.