Select to view content in your preferred language

Python script question

320
6
10-23-2024 11:27 AM
Labels (1)
JRR
by
Emerging Contributor

UseThis = 2
##
arcpy.SelectLayerByLocation_management("BIRDLINE_LAYER", "intersect", "BigPoly", 0, "new_selection")
arcpy.SelectLayerByAttribute_management('BIRDLINE_LAYER', 'SUBSET_SELECTION', '"Route" = 2')
#arcpy.SelectLayerByAttribute_management('BIRDLINE_LAYER', 'SUBSET_SELECTION', '"Route" = UseThis')
#arcpy.SelectLayerByAttribute_management('BIRDLINE_LAYER', 'SUBSET_SELECTION', "UseThis" )

Only the first 'SUBSET_SELECTION', works.   How can I use the value of 'UseThis' ??

0 Kudos
6 Replies
CodyPatterson
Frequent Contributor

Hey @JRR 

I think you need to pass the input as a function string:

UseThis = 2
arcpy.SelectLayerByLocation_management("BIRDLINE_LAYER", "intersect", "BigPoly", 0, "new_selection")
arcpy.SelectLayerByAttribute_management('BIRDLINE_LAYER', 'SUBSET_SELECTION', '"Route" = 2')
arcpy.SelectLayerByAttribute_management('BIRDLINE_LAYER', 'SUBSET_SELECTION', f'"Route" = {UseThis}')

Cody

0 Kudos
JRR
by
Emerging Contributor

That seems to only apply to rasters.  Thanks for your response!

arcpy.SelectLayerByAttribute_management('BIRDLINE_LAYER', 'SUBSET_SELECTION', f'"Route" = {UseThis}')

show invalid expression

0 Kudos
CodyPatterson
Frequent Contributor

Hey @JRR 

Ah alright I see, it may be because your Route attribute is expected to be a certain data type, if it's an integer it would be something like this:

arcpy.SelectLayerByAttribute_management('BIRDLINE_LAYER', 'SUBSET_SELECTION', f'"Route" = {UseThis}')

Otherwise, if it is a string, it should be this here:

arcpy.SelectLayerByAttribute_management('BIRDLINE_LAYER', 'SUBSET_SELECTION', f'"Route" = \'{UseThis}\'')

This escapes the single quotes to be used in the SQL. Hopefully this solves it for you!

Cody

0 Kudos
JRR
by
Emerging Contributor

Neither of these lines work.

JRR_0-1729804855506.png

 

0 Kudos
CodyPatterson
Frequent Contributor

Hey @JRR 

The errors are not very descriptive using IDLE, you may have better luck and better error reporting when using Visual Studio Code instead.

Give this a shot here, this builds the query outside of the function:

UseThis = 2

arcpy.SelectLayerByLocation_management("BIRDLINE_LAYER", "intersect", "BigPoly", 0, "new_selection")

sql_expression = f'"Route" = {UseThis}'

print(sql_expression) # Just use this to test to see if it's actually printing anything and that the expression looks correct

arcpy.SelectLayerByAttribute_management('BIRDLINE_LAYER', 'SUBSET_SELECTION', sql_expression)

I would ensure that the print statement is in there for debugging.

Cody

0 Kudos
JRR
by
Emerging Contributor

I tried with no success.   Sorry to be so late in responding.. traveling.

Sent the code and a sample data set.

0 Kudos