ArcPy: End script if condition is true...

12038
5
Jump to solution
09-15-2015 02:15 PM
MaribethMilner
New Contributor III

PythonWin; ArcGIS 10.3

I'm trying to implement an exit function that was posted on another site (http://gis.stackexchange.com/questions/1015/how-to-have-a-python-script-self-terminate-in-arcmap10), but it's not working...

# Create function to exit script

def finish(arg=None):

    try:

        sys.exit(arg)

    except SystemExit:

        pass

# Check for nodata (Note: Shapefiles don't support nodata - ArcGIS turns them into zeroes)

if pHx10 == 0:

    print "The point you selected is water or otherwise undefined"

    finish()

else:

    print "Point's data is defined"

When I input a point that's associated with nodata (i.e. pHx10==0)... the script doesn't exit.

Also... there must be a way to end the else statement without using a print statement. Break and continue are used in while and for statements. So what do you use for an if statement?

I'm new to ArcGIS and don't know Python.

0 Kudos
1 Solution

Accepted Solutions
MaribethMilner
New Contributor III

I'm new to this site... as well as ArcPy (which is what I meant to say in the first post)...

...and this is the only way I could find to complete this thread.

1) I didn't import sys

2) The original link that I cited had a secondary link to an ESRI example...

http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//000v000000vp000000.htm

Turns out I didn't need the function. Just needed to add sys.exit(0) (without the else statement - thanks for that)...

# Check for nodata. Nodata isn't supported in shapefiles. Becomes zero.

if pHx10 == 0:

    print "The point you selected is water or otherwise undefined."

    print "To identify a new point near your target area..."

    print "a) In ArcMap... turn on soc250."

    print "b) Use the Go To XY and zoom tools to zoom into your target,"

    print "   position your cursor over data near your target area"

    print "   and note the location in the status bar (bottom)"

    sys.exit(0)

    print "didn't exit"

All is well.

View solution in original post

5 Replies
DarrenWiens2
MVP Honored Contributor

Are you sure that your data = 0? Try setting pHx10 = 0 before the if statement, and see if the script terminates.

Otherwise, post your complete script, showing how you set pHx10.

As for the else statement, you're not required to provide an else, at all, if you don't want to do something.

0 Kudos
MaribethMilner
New Contributor III

Yes. I use the ExtractMultiValuesToPoints function to extract the data to a shapefile and was surprised to find zero values for each raster that had nodata at the point I entered.

I originally typed if pHx10 = 0, and PythonWin wouldn't run the script until I set it to pHx10 == 0.

Just tried if pHx10 < 1. Still didn't work.

Here's the code...

import arcpy

from arcpy.sa import *

arcpy.CheckOutExtension("Spatial")

from arcpy import env

# set environment

env.workspace = "D:/.../Data"

env.scratchWorkspace = "D:/...Data"

env.scratchWorkspace = env.scratchFolder

env.overwriteOutput = True

# Create function to exit script

# http://gis.stackexchange.com/questions/1015/how-to-have-a-python-script-self-terminate-in-arcmap10

def finish(arg=None):

    try:

        sys.exit(arg)

    except SystemExit:

        pass

# Create point file (eventually from user inputs)

arcpy.CreateFeatureclass_management("D:/.../Data/Out", "selpoint.shp", "POINT", "", "DISABLED", "DISABLED", "D:/.../Data/Data8-26-15-0001.shp")

fc = "D:/.../Data/Out/selpoint.shp"

cursor = arcpy.da.InsertCursor(fc, ["SHAPE@XY"])

xy = (31.9, 0.34)

cursor.insertRow([xy])

del cursor

del xy

# Extract grid values associated with the point

ExtractMultiValuesToPoints(fc, [["aikm", "aikm"], ["bio4km", "bio4km"], ["avggddkm", "avggddkm"], ["soc250", "soc250"], ["ph250x10", "ph250x10"], ["sand250", "sand250"], ["dem500", "dem500"], ["latdx100", "latdx100"]],"NONE")

# Assign extracted values to variables; Note: latdx100 = |latitude| x 100

cursor = arcpy.SearchCursor(fc)

for row in cursor:

    ai = row.getValue('aikm')

    bio4 = row.getValue('bio4km')

    soc = row.getValue('soc250')

    pHx10 = row.getValue('ph250x10')

    sand = row.getValue('sand250')

    dem = row.getValue('dem500')

    latx100 = row.getValue('latdx100')

del cursor

del row

# Check for nodata. Nodata isn't supported in shapefiles. Becomes zero.

if pHx10 < 1:

    print "The point you selected is water or otherwise undefined."

    print "To identify a new point near your target area..."

    print "a) In ArcMap... turn on soc250."

    print "b) Use the Go To XY and zoom tools to zoom into your target,"

    print "   position your cursor over data near your target area"

    print "   and note the location in the status bar (bottom)"

    finish()

else:

    print "Point's data is defined"

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

The Python sys documentation explains what is going on:

sys.exit([arg])

Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.

...

Since exit() ultimately “only” raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted.

You are raising the SystemExit exception, promptly trapping it, and then ignoring it with your pass statement.

DanPatterson_Retired
MVP Emeritus

why arent you passing 0 to finish? ie finish(0) instead of finish

you should alway set up your condition checking in the postive where possible. for example

def finish(arg=None):
    if arg:
        print("\nargument is {} and I can carry on".format(arg))
    else:
      print("\nargument is {} and I should quit".format(arg))
    return arg

  

for i in [0,1,None,'a',2]:
    result=finish(i)
    print("made it here with...{}".format(result))

results in the following

argument is 0 and I should quit
made it here with...0

argument is 1 and I can carry on
made it here with...1

argument is None and I should quit
made it here with...None

argument is a and I can carry on
etc 

when you run finish without arguments...

>>> finish()
argument is None and I should quit
MaribethMilner
New Contributor III

I'm new to this site... as well as ArcPy (which is what I meant to say in the first post)...

...and this is the only way I could find to complete this thread.

1) I didn't import sys

2) The original link that I cited had a secondary link to an ESRI example...

http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//000v000000vp000000.htm

Turns out I didn't need the function. Just needed to add sys.exit(0) (without the else statement - thanks for that)...

# Check for nodata. Nodata isn't supported in shapefiles. Becomes zero.

if pHx10 == 0:

    print "The point you selected is water or otherwise undefined."

    print "To identify a new point near your target area..."

    print "a) In ArcMap... turn on soc250."

    print "b) Use the Go To XY and zoom tools to zoom into your target,"

    print "   position your cursor over data near your target area"

    print "   and note the location in the status bar (bottom)"

    sys.exit(0)

    print "didn't exit"

All is well.