Convert Python Script to Tool with Parameters

165
5
Jump to solution
04-26-2021 10:06 AM
AndrewClark2
New Contributor III

HI, 

I have a script that runs perfectly fine using variables for the inputs. As soon as I turn them to parameters, I am running into a "RUN TIME ERROR" with no details. I cannot for the life of me figure out the issue. Any suggestions? The 

Thanks!

Andrew

 

import arcpy as ap
import numpy as np
import os 

# set environmental variables
ws=ap.GetParameterAsText(0)
gdb = ap.GetParameterAsText(1)
scratch = ap.GetParameterAsText(2)

# Set default geodatabase as workspace
ap.env.workspace = gdb

# Allow files to be overwritten by python code
ap.env.overwriteOutput = True

# Analysis Files
pc = ap.GetParameterAsText(5)
nds = ap.GetParameterAsText(3)
nd_layer_name = "NetworkDataSet"
Output_FD = ap.GetParameterAsText(7)

Imp = ap.GetParameterAsText(6)
Impedance = []
for x in Imp.split(';'):
    Impedance.append(float(x))
    ap.AddMessage(x)
    ap.AddMessage(Impedance)

### School Network Service Area ###

# Create a network dataset layer and get hte desired travel mode
ap.nax.MakeNetworkDatasetLayer(nds,nd_layer_name)
nd_travel_modes = ap.nax.GetTravelModes(nd_layer_name)
travel_mode = nd_travel_modes[ap.GetParameterAsText(4)]
ap.AddMessage("Create network dataset")

# Instantiate a ServiceArea solver object
service_area = ap.nax.ServiceArea(nd_layer_name)
search_query=[['RoadsNetwork',"'STREET' IS NOT NULL And 'STREET' <> ''"]]
search_criteria=[['RoadsNetwork','SHAPE'],['NetworkDataSet_Junctions','NONE']]
search_tolerance = 500

# Set properties
service_area.distanceUnits = ap.nax.DistanceUnits.Meters
service_area.travelMode = travel_mode
service_area.outputType = ap.nax.ServiceAreaOutputType.Polygons
service_area.geometryAtOverlap = ap.nax.ServiceAreaOverlapGeometry.Overlap
service_area.searchQuery=search_query
service_area.searchTolerance=search_tolerance
service_area.searchToleranceUnits = ap.nax.DistanceUnits.Meters
service_area.polygonBufferDistanceUnits=ap.nax.DistanceUnits.Meters
service_area.polygonBufferDistance=50
service_area.polygonDetail=ap.nax.ServiceAreaPolygonDetail.High

for n in Impedance:
    ap.AddMessage(n)
    service_area.defaultImpedanceCutoffs = [n]

    fd = str(n)+'m'

    fm_fac = service_area.fieldMappings(ap.nax.ServiceAreaInputDataType.Facilities,True)
    fm_fac["Name"].mappedFieldName = 'PCODE'
    ap.AddMessage("Create a network Service Area {} network analysis layer".format(fd))

    # Load Inputs
    service_area.load(ap.nax.ServiceAreaInputDataType.Facilities, pc,field_mappings=fm_fac, append=False)
    ap.AddMessage("Facilities loaded!")
    
    # Solve the analysis
    result = service_area.solve()

    ap.AddMessage("Create a network Service Area {} network analysis layer".format(fd))
    ap.AddMessage(result)
    
    expresult = os.path.join(Output_FD,"RoadNtwkBuf_"+fd)
    
    # Export Feature Class
    result.export(ap.nax.ServiceAreaOutputDataType.Polygons, expresult)
    
    for field in ap.ListFields(expresult):
        ap.AddMessage(field.name)
        if field.required == False:
            if field.name not in ['Name','ToBreak']:
                ap.management.DeleteField(expresult,'{}'.format(field.name))
            
    ap.management.AlterField(expresult,'Name','PCODE',clear_field_alias = "CLEAR_ALIAS")
    ap.management.AlterField(expresult,'ToBreak','BufferSize',clear_field_alias = "CLEAR_ALIAS")
    
    ap.management.CalculateField(expresult,'PCODE','!PCODE![0:6]')
    
    ap.AddMessage('Calculated service area for {}-m service area buffer'.format(n))

 

Traceback (most recent call last):
File "...\Scripts\01_NetworkBuffers.py", line 78, in <module>
result.export(ap.nax.ServiceAreaOutputDataType.Polygons, expresult)
RuntimeError
Failed to execute (NetworkBuffers).

AndrewClark2_1-1619456738747.png

Tags (3)
0 Kudos
1 Solution

Accepted Solutions
DavidPike
MVP Frequent Contributor

hmm, how about changing the output location to just the GDB, possibly a mix of coordinate systems? What's with C:\Users\C:\Users\ for params 3 and 5?

Although you'd expect it to be the same as the input - and as you ay the tool does work a a standalone script.

I know you have the overwriteOutput set but still try making sure there's no locks/existing data etc. as part of the testing.

View solution in original post

0 Kudos
5 Replies
DavidPike
MVP Frequent Contributor

I don't see the full filepaths listed in the tool, looks more like they were dragged as layers - possibly try the full file path for GetParmeterAsText to work, or just as layers/datasets with GetParameter(n).  What data types do you have set?

I'd guess this is causing 'result' to be empty.

0 Kudos
AndrewClark2
New Contributor III

Thanks for the idea, but when printing out the parameters, they are all paths: 

p(0): C:\Users\...\03_WorkingData\HEAL_ActiveLivingIndex
p(1): C:\Users\...\03_WorkingData\HEAL_ActiveLivingIndex\HEAL_ActiveLivingIndex.gdb
p(2): C:\Users\...\03_WorkingData\HEAL_ActiveLivingIndex\Scratch.gdb
p(3): C:\Users\C:\Users\...\03_WorkingData\HEAL_ActiveLivingIndex\HEAL_ActiveLivingIndex.gdb\RoadNetwork\NetworkDataSet
p(5): C:\UsersC:\Users\...\03_WorkingData\HEAL_ActiveLivingIndex\HEAL_ActiveLivingIndex.gdb\TESTPC
p(6): 400;800;1000
p(7): C:\Users\C:\Users\...\03_WorkingData\HEAL_ActiveLivingIndex\HEAL_ActiveLivingIndex.gdb\Analysis

I also get the following when printing out the result feature: 

<arcgisscripting.ServiceAreaResult object at 0x00000223C8FBAD10>

So I believe the 'result' is not empty

0 Kudos
DavidPike
MVP Frequent Contributor

hmm, how about changing the output location to just the GDB, possibly a mix of coordinate systems? What's with C:\Users\C:\Users\ for params 3 and 5?

Although you'd expect it to be the same as the input - and as you ay the tool does work a a standalone script.

I know you have the overwriteOutput set but still try making sure there's no locks/existing data etc. as part of the testing.

View solution in original post

0 Kudos
AndrewClark2
New Contributor III

You got it! Projection issue! Local dataset combined with a National dataset so mixing UTM Z17 with Lambert.... so annoying

0 Kudos
DanPatterson
MVP Honored Contributor

parameter 4?

seems to be missing, or it is my eyes


... sort of retired...
0 Kudos