TransWikia.com

Changing hard coded variable value to user input in Python script with ArcPy

Geographic Information Systems Asked by Mudassar Shah on August 30, 2021

I have exported "Con Tool" script from ModelBuilder. The model has two input parameters one is the DEM and the second is "Long Variable". When I run the model it executes perfectly fine but as I import the script to tool box and assign the variables and type and run them the Python log shows errors.
I believe the script is taking the variable name instead of its value.

How do I fix that?

This is the script:

# ---------------------------------------------------------------------------
# conmodelscript.py
# Created on: 2020-07-24 11:51:39.00000
#   (generated by ArcGIS/ModelBuilder)
# Usage: conmodelscript <DEM> <Input_Value> 
# Description: 
# ---------------------------------------------------------------------------

# Import arcpy module
import arcpy

# Script arguments
DEM = arcpy.GetParameterAsText(0)

Input_Value = arcpy.GetParameterAsText(1)

# Local variables:
Long = "1"
Output = "C:Users92347Desktoptestoutput.tif"

# Process: Con
arcpy.gp.Con_sa(DEM, Long, Output, "", "Value<=%Input Value%")

This is the model

enter image description here

enter image description here

enter image description here

enter image description here

This is how I add and run the script

enter image description here

enter image description here

enter image description here

enter image description here

One Answer

Your code has inherited the ModelBuilder inline substitution syntax, which you need to fix to make the code work.

Change this line:

arcpy.gp.Con_sa(DEM, Long, Output, "", "Value<=%Input Value%")

to:

arcpy.gp.Con_sa(DEM, Long, Output, "", "Value <= " + Input_Value)

As you set the variable Input_Value using GetParameterAsText() it is converting the number into a string so a simple concatenation is all that is required for the where clause in Con().

Answered by Hornbydd on August 30, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP