Exiting Early with sys.exit()

I often like to exit early from Jython functions I write by returning. This helps keep nested if conditions to a minimum.

For instance, I’d check if data in arguments are valid and if they are not then return right away.

But I couldn’t do this when writing event handlers because event handlers are not functions. I could wrap the event handlers in functions but that’s extra work and an extra level of indentation.

But with Ignition release 7.1.2, there is now a way to exit early from event handler code. Calling sys.exit() kills the script it is in. Code past sys.exit() is not run.

1 Like

I also use exiting early for testing code. I put code I want to test at the top of a function or event handler, and then exit early with return or sys.exit() so all the other code that I’m not testing isn’t run.

Yep, this is pretty handy. Don’t forget to do a [tt]import sys[/tt] first!

What’s the difference between exit() and quit()?

exit() and quit() are the same. Both names just exist for convenience in the python shell.

sys.exit() is for usage in scripts, though it also does pretty much the same as the regular exit() and quit().

Dead thread, I know but I can’t get the sys.exit() function to work in a button script. Any suggestions?

What do you mean? As described above, sys.exit() kills the interpreter running that one event script, not the whole client. To kill the whole client, try this:

from java.lang import System
System.exit(0)

I mean I have a script with a confirmation dialog box. An action is taken when either “Yes” or “No” are selected. I want the script to stop running when the “Cancel” option is selected as well. When I use sys.exit() I get an error saying the name sys is not defined.

Do you have an import sys in your script?

2 Likes

You can also just use system.util.exit(), which gives any client shutdown script a chance to run (and saves the import).

3 Likes

Yeah, that’d be better. (-:

and saves the import

And 3 keystrokes