Stopping a conditional loop with the Esc key in Python

Is there an elegant way to do this? I have a script with a conditional loop (while…) that will rotate an object. I want it to terminate when the user presses the Escape key. I’m trying a bunch of ugly hacks, but I thought if there is a “proper” way to do this I’m best to learn that right from the start.

Thanks,

Dan

1 Like

Thanks Menno. I’ll see if I can implement this.

Dan

Here is an example on how to use it:

import scriptcontext
import rhinoscriptsyntax as rs

strView=rs.CurrentView()

# Rotate camera until ESC
while True:
    rs.RotateView(strView,direction=0, angle=5)
    #check for esc press
    if scriptcontext.escape_test(False):
        print "ESC pressed "
        break      #get out of the loop

print "View rotation stopped by ESC"

Last line is just to show that the script continues after ESC breaks the loop since “break” is used.
If you want to stop the script from continuing then you have to use “exit()” instead of “break”
(as far as I know)

2 Likes

That worked like a champ, thank you!

Dan

You are welcome!
I need the repetition any way :smile:
Trying to learn a new language with new rules and new possibilities take time…

It’s a daunting task, to say the least. I’ve made it my goal for 2014 to convert all of my existing scripts into Python, and in the process, I hope to learn Python. I have a long way to go, and many questions to ask, but I will do my research first. Google is coming in pretty handy these days!

Dan

Hi all,

this:

    if i%100==0 and scriptcontext.escape_test(False):

works great in the in-built editor. However, if I am using this snippet directly inside a button through -_RunPythonScript (), which I am dependent on in my case, it does not recognize ESC being pressed during the loop sequence. Any ideas?

Best
M

Hi all this works great but now I’m stuck have a script that runs multiple Rhino commands inside of its loop…
but the escape_test wont break the loop especially if a rhino command has started…
but as I was writing this would calling rs.getpoint before or after the rhino commands give the program more time to recognize and break the loop… trying it now…

Nooope lol that did not work but it does give a nice much need time delay between rhino commands