ApplySymbologyFromLayer_management inside toolbox script doesn't work

861
9
08-20-2021 02:05 AM
Labels (1)
dstrigl
New Contributor III

Dear esri community,

I am rather new to ArcGIS Pro, but have really good experience with Python.

Now I created my first little toolbox with a script with takes an input feature layer and creates another output feature layer from the input by just taking a random sample of features from it.

This works fine, but now I also want to apply the same symbology from the input feature layer to the new created output feature layer.

Therefore I execute ApplySymbologyFromLayer_management at the end of the script.

This runs without an error, but doesn't update/change the symbology of the new created output feature layer.

Interesting is, if I call the same statement (ApplySymbologyFromLayer_management) inside the Python command prompt of ArcGIS Pro it works.

I also tried to execute the ApplySymbologyFromLayer_management command inside a second script of my toolbox, but this also doesn't work.

Anyone has an idea what's the problem?

Thanks and regards,

Daniel.

 

 

9 Replies
DanPatterson
MVP Esteemed Contributor
dstrigl
New Contributor III

Thanks for your fast reply. Yeah, this could be the reason. Thanks! Than I have to wait until it will be fixed.

HannesZiegler
Esri Contributor

Hi dstrigl, could you try using this approach:

import arcpy

params = arcpy.GetParameterInfo()
inlyr = params[0]
outlyr = params[1]

res = arcpy.management.Copy(inlyr.valueAsText, outlyr.valueAsText)
outlyr.symbology = inlyr.valueAsText

 

Set your tool's parameters like this: 

HannesZiegler_0-1629479326445.png

 

The above approach is described here and works in my testing.

Please let me know if this solution works for you!

0 Kudos
dstrigl
New Contributor III

Hi Hannes,

thanks for your response.

Sorry, but your solution doesn't work in my toolbox script.

Maybe, it's my fault because at the moment I am not so really familiar with the different types of Python scripts in ArcGIS Pro (.tbx and .pyt) and the different data types.

At the moment I have created my own little toolbox with the following Python code:

 

import random
import arcpy

class Toolbox(object):
    def __init__(self):
        """Define the toolbox (the name of the toolbox is the name of the
        .pyt file)."""
        self.label = "MyToolbox"
        self.alias = ""

        # List of tool classes associated with this toolbox
        self.tools = [SelectSampleByPercent]

class SelectSampleByPercent(object):
    def __init__(self):
        """Define the tool (tool name is the name of the class)."""
        self.label = "SelectSampleByPercent"
        self.description = ""
        self.canRunInBackground = False

    def getParameterInfo(self):
        """Define parameter definitions"""

        # First parameter
        param0 = arcpy.Parameter(
            displayName="Input Features",
            name="in_features",
            datatype="GPFeatureLayer",
            parameterType="Required",
            direction="Input",
        )

        # Second parameter
        param1 = arcpy.Parameter(
            displayName="Proportion of sample (in %)",
            name="in_range",
            datatype="GPLong",
            parameterType="Required",
            direction="Input",
        )
        param1.filter.type = "Range"
        param1.filter.list = [0, 100]
        param1.value = 10

        # Third parameter
        param2 = arcpy.Parameter(
            displayName="Output Features",
            name="out_features",
            datatype="DEFeatureClass",
            parameterType="Required",
            direction="Output",
        )

        params = [param0, param1, param2]

        return params

    def isLicensed(self):
        """Set whether tool is licensed to execute."""
        return True

    def updateParameters(self, parameters):
        """Modify the values and properties of parameters before internal
        validation is performed.  This method is called whenever a parameter
        has been changed."""
        return

    def updateMessages(self, parameters):
        """Modify the messages created by internal validation for each tool
        parameter.  This method is called after internal validation."""
        return

    def execute(self, parameters, messages):
        """The source code of the tool."""
        arcpy.env.overwriteOutput = True

        in_features = parameters[0].value
        percent = parameters[1].value
        out_features = parameters[2].value

        in_catalog_path = arcpy.Describe(in_features).catalogPath

        feature_count = arcpy.GetCount_management(in_catalog_path).getOutput(0)
        count = int(float(feature_count) * float(percent) / 100.0)

        oids = [oid for oid, in arcpy.da.SearchCursor(in_catalog_path, "OID@")]

        oid_field_name = arcpy.Describe(in_catalog_path).OIDFieldName

        random_oids = random.sample(oids, count)
        oids_str = ", ".join(map(str, random_oids))

        sql_exp = f"{arcpy.AddFieldDelimiters(in_catalog_path, oid_field_name)} IN ({oids_str})"

        arcpy.Select_analysis(in_catalog_path, out_features, sql_exp)
        arcpy.management.ApplySymbologyFromLayer(arcpy.Describe(out_features).baseName, in_features)

        return

 

Maybe you see some errors inside the script?!

I would like to pick some samples (randomly from the source feature layer) and write it to another new output layer, together with the original symbology from the source layer.

Regards,

Daniel.

 

0 Kudos
HannesZiegler
Esri Contributor

I just ran this toolbox and it applies the symbology to the output, what version of Pro are you working with?

0 Kudos
dstrigl
New Contributor III

ArcGIS Pro 2.6.5

0 Kudos
HannesZiegler
Esri Contributor

Are you constrained to 2.6.5, or are you able to upgrade to a more recent version?

For 2.7 and greater you may also try arcpy.setParameterSymbology.

 

arcpy.SetParameterSymbology(2, in_features)

 

 

0 Kudos
dstrigl
New Contributor III

Hi Hannes,

thanks again for your response!

I just ran this toolbox and it applies the symbology to the output

That's great to hear 🙂.

> Are you constrained to 2.6.5, or are you able to upgrade to a more recent version?

I have to verify and try to get an newer version. Afterwards I will try again and give you feedback.

Thanks and regards,

Daniel.

 

LeandraGordon
Occasional Contributor II

ApplySmbologyfromLayer is still very buggy even in 2.8.1
I can get some layers to work if I create the LYRX files from layers with a different name but not all of them

0 Kudos