Jython Script Exit

I have some scripts that utilize several if statements. If the script enters a certain one of the if statements, I want the script to stop execution and exit. I’ve been doing this with

from sys import exit
exit()

Do I need to do this, or is there a better, more appropriate way to do this?

You can simply call “return” to exit from the script at any point.

3 Likes

I think this will work, but only if I define the entire script as a function. Just in case someone else wonders about this.

2 Likes

What did you end up doing?

Is exit() okay?
Do I have to import that library?

I have people submitting, but I want them not to be able to if some values are null.
I don't import the library and use exit(), seems to work, but I don't know if that means it is the way to perform the script.

Validate that all fields that you need are not null and then execute, otherwise just fall through. Though you should give the user some indication of why there submission was not accepted.

1 Like

Yah, I should make some exception logic that sets text.
If I could just remember where you showed me that.
I remember seeing it, and even implementing it for a time once.

if range(dataOut.getRowCount()) == []:
	print 'yes'
	exit()
print 'did not stop'

Right now, this code snippet is performing as I hoped in the script console.
I am still not clear on if exit() is good to use though.
Return won't work, says 'return' outside function.

I would strongly recommend that you not use exit. This isn't a complete snip-it of code, where ever you are really going to place it, will be in a function of some type, so return will work.

1 Like

Thanks

Is there not another way to end a script such that it will work in the script console and where the code will be placed?

I think I only struggle with this because return is problematic for me in the script console.

Just put it in a dummy function, if you really must use return.

Other wise, either you get two print statements or you only the last one.

3 Likes

You can also express almost any logic without resorting to early return/exit with a little refactoring.

Your original example is simple but still demonstrates the point:

if range(dataOut.getRowCount()) == []:
	print 'yes'
else:
	print 'did not stop'
2 Likes

Thanks

I read that returning early is better than not.

Guess I have to pick between:
Returning early where I place the code while using exit in the script console
Returning early where I place the code while using a dummy function with return early in the script console
Or placing my code inside the if statement

Also, I apologize for writing:
if range(dataOut.getRowCount()) == []:
I was learning how to find out if my query came back empty.
if dataOut.getRowCount() ==0:

This:

if dataOut.rowCount == 0:

Is more performant.

You can also use the fact that 0 is considered falsey and just write

if dataOut.rowCount:
2 Likes