#ArcPy
ArcPy keep highlight & modify zoom level
I recently created a script tool to automate creating layouts for mapped objects that all have to look a certain way. I was wondering if anyone knows how to keep selected features highlighted in the layout (they appear highlighted in the layout screen after the script is run but are not highlighted in the PDF/exported layout)? I run the script tool with the desired elements selected. Before some formatting stuff, what I believe is the most relevant script is as follows: lyt = aprx.listLayouts(f"{lyt_name}*")[0] title = lyt.listElements("TEXT_ELEMENT", "Title")[0] then some formatting of text strings that doesn't have to do with the selection, including the creation of the plural, PINStr, PLAT, TWP and ADD variables, and then the layout is adjusted: new_text = f'{before_or_after}\nPIN{plural}: {PINStr}\nDeed/Plat: {PLAT}\nAddress: {ADD}' title.text = new_text # zoom layout to active view mf = lyt.listElements('mapframe_element')[0] mf.zoomToAllLayers(True) and then the layout is exported to a PDF: arcpy.management.CreateFolder(r"[file path]\{} TWP".format(TWP), PLATPath) # create new folder exp = arcpy.mp.CreateExportFormat("PDF", path) disOpt = arcpy.mp.CreateExportOptions("DISPLAY") disOpt.outputAsImage = True disOpt.imageCompression = "JPEG2000" disOpt.imageCompressionQuality = 50 disOpt.imageQuality = "NORMAL" lyt.export(exp) I feel like the answer is in the display options, but I can't find anything here or on forums. Are there any links to places where this question has already been answered that I couldn't find?
gis.stackexchange.com
November 12, 2026 at 6:29 AM
having a rare and beautiful week where arcpy is my friend and things work
November 4, 2026 at 9:46 PM
#TIL if this #ArcPy API fails with an OSError and no hints in the traceback message while trying to extract an .mpkx file, try using 7Zip (not OS tools) to open the .mpkx file, extract the contents (e.g. geodatabase) manually, and then add it into an ArcGIS project.
doc.esri.com/en/arcgis-pr...
Extract Package (Data Management Tools) | ArcGIS Pro documentation
Extracts the contents of a package to a specified folder.
doc.esri.com
November 4, 2026 at 7:16 PM
Michael Cattell: Automating Map Production Using ArcPy

Use code and database queries to build and consistently style a series of similarly-themed maps.

#NACIS2026
October 21, 2026 at 7:08 PM
Applying Color Ramp in PyQGIS?
I extensively use ArcPy, recently needed to apply a specific color ramp on a single band raster and export it. Arcpy does not allow me to apply color ramp and save the raster with the applied color ramp. However, QGIS has the option to do that. I created a new color ramp in QGIS 2.18.20 and name it to "Yield", which is 28th (defaultColorRampNames[27]) item in the color ramp list. Is there any PyQGIS codes that can automatically apply the color ramp to the raster. I have the codes to save the raster after applying the color ramp but struggling to find a way to apply that. Followed the codes from Using QGIS GUI predefined colorramps in Python console / PyQGIS? - but first couples of lines are working not the last three lines. The following codes are working - #accessing the raster layer vl = iface.activeLayer() ## get default style myStyle = QgsStyleV2().defaultStyle() ## get a list of default color ramps [u'Blues', u'BrBG', u'BuGn'....] defaultColorRampNames = myStyle.colorRampNames() ## setting ramp to "Yield" which was recently created ramp = myStyle.colorRamp(defaultColorRampNames[27]) But, the codes provided below seems like for a shapefile, not sure what to use for the raster layer # set up an empty categorized renderer and assign the color ramp renderer = QgsCategorizedSymbolRendererV2(field, []) renderer.setSourceColorRamp(ramp) vl.setRendererV2(renderer)
gis.stackexchange.com
October 20, 2026 at 6:51 AM
words for the words thread
October 20, 2026 at 1:53 AM
Converting PyQGIS script to processing tool with user input
My code selects points in a layer by date and creates a new layer from them. I want to make this a processing tool where the user can choose the date and run the script. I'm brand new to QGIS, but I've created several tools like this for ArcMap with ArcPy - that process involves adding GetParameterAsText() for user inputs and appending your script to a toolbox. I have been searching and watching videos, but I haven't found a way to do something similar in QGIS yet. Script snippet below (this is not the complete script, but it includes the date that I'd like to replace with user input): import qgis.utils import PyQt5 from PyQt5 import QtPrintSupport from PyQt5.QtPrintSupport import QPrinter from qgis.utils import iface from qgis.PyQt.QtCore import (QCoreApplication, QSizeF) from PyQt5.QtGui import (QColor, QPageLayout, QPainter) from qgis.core import (QgsProcessing, QgsProcessingAlgorithm, QgsProcessingException, QgsProcessingContext, QgsProcessingParameterString, QgsProcessingOutputVectorLayer, QgsProcessingOutputRasterLayer, QgsProcessingOutputString, QgsProcessingParameterNumber, QgsVectorLayer, QgsVectorFileWriter, QgsRasterLayer, QgsDataSourceUri, QgsProject, Qgis, QgsMapRendererCustomPainterJob) #select features temporaryCompaction = QgsProject.instance().mapLayersByName('Temporarycompaction')[0] iface.setActiveLayer(temporaryCompaction) iface.mapCanvas().setSelectionColor(QColor('green')) expression = "to_date(Date) = to_date('2021-09-23', 'yyyy-MM-dd')" temporaryCompaction.selectByExpression(expression) #create layer from selected features and import to Layers fn = r'U:\skelley\public\QGISstuff\PacTrustMergin-2test/newLayer.gpkg' writer = QgsVectorFileWriter.writeAsVectorFormat(temporaryCompaction, fn, 'utf-8', driverName='GPKG', onlySelected=True) selected_layer = iface.addVectorLayer(fn, '', 'ogr') del(writer)
gis.stackexchange.com
October 13, 2026 at 7:07 AM
A Framework for Automated Multi-Source Satellite Data Analytics and LLM-Based Report Generation

Hind Yousif Alhammadi, Isam Mashhour Al Jawarneh

#arXiv #cs.AI #astro-ph.IM
A Framework for Automated Multi-Source Satellite Data Analytics and LLM-Based Report Generation
This paper presents the workflow for building an automated ArcGIS Pro tool using ArcPy to extract the Land Surface Temperature (LST) from Landsat 7, 8 and 9 datasets. The tool eliminates the need for manual band selection and repetitive raster computations by automating the multi-step workflow of r…
arxiv.org
October 8, 2026 at 1:27 AM
You may find better options on reddit. There may be good tutorials on youtube to get you started as well. This was top of my search results:
www.youtube.com/watch?v=6Y9h...
GIS Python Tutorial: Getting Started with ArcPy and VS Code #GIS #Python #Code #ArcPy
YouTube video by GIScience
www.youtube.com
October 6, 2026 at 11:02 PM
A Framework for Automated Multi-Source Satellite Data Analytics and LLM-Based Report Generation

Hind Yousif Alhammadi, Isam Mashhour Al Jawarneh

#arXiv #cs.AI #astro-ph.IM
A Framework for Automated Multi-Source Satellite Data Analytics and LLM-Based Report Generation
This paper presents the workflow for building an automated ArcGIS Pro tool using ArcPy to extract the Land Surface Temperature (LST) from Landsat 7, 8 and 9 datasets. The tool eliminates the need for manual band selection and repetitive raster computations by automating the multi-step workflow of r…
arxiv.org
October 7, 2026 at 1:07 AM
Using field mapping with ArcPy
I'm having trouble trying to understand how field mapping works in ArcPy. I'm relatively new to Python. In the below example, I want to take a shapefile and append it to a feature class but I want to use the field map parameter so the fields from the shapefile go to the correct field names in the feature class. I successfully built this out in ModelBuilder and exported the Python script (see below) but so much of it doesn't make sense. For example, what are all these different codes... -1, 0, #, true, false, etc? There seems to be no documentation anywhere online on the meaning behind these codes. I read that I can use the fieldmapping() class as a parameter in this script but have been unable to incorporate that? If you know a much easier way (via python) to field map then using the above methods, I'm open to those suggestions. The code below is only a simple test that I created, so I can hopefully understand field mapping better but in the long run I want to this to be able to handle a LOT of fields from many different shapefiles. Source shapefile schema: Name, Code, Date Target feature class schema: Description, Num, Date # Import arcpy module import arcpy # Local variables: New_Shapefile_shp = "C:\\New_Shapefile.shp" New_Featureclass__2_ = New_Shapefile_shp New_Featureclass = "C:\\Target.gdb\\New_Featureclass" # Process: Append arcpy.Append_management("C:\\New_Shapefile.shp", New_Featureclass, "NO_TEST", "DESCRIPTION \"DESCRIPTION\" true true false 150 Text 0 0 ,First,#,C:\\New_Shapefile.shp,Name,-1,-1;NUM \"NUM\" true true false 4 Long 0 0 ,First,#,C:\\New_Shapefile.shp,Code,-1,-1;DATE \"DATE\" true true false 8 Date 0 0 ,First,#,C:\\New_Shapefile.shp,Date,-1,-1", "")
gis.stackexchange.com
September 24, 2026 at 12:20 AM
"AttributeError: 'FeatureLayer' object has no attribute 'overwrite'" error when overwriting feature service with CSV using ArcPy
I am trying to download a CSV from our project database and then append this to a feature service in AGOL. import os import requests import csv import arcpy from requests.auth import HTTPBasicAuth from arcgis.gis import GIS print('Environment variables loaded.') API_URL = 'https://web.lucion.co.uk/api/' API_ENDPOINT = 'jobs/get' USERNAME = 'removed' PASSWORD = 'removed' if USERNAME == 'my_email' or PASSWORD == 'my_password': raise Exception("You need to change your email and password") # Define the json post data json_data = { "filters": [ { "office.company": 11 } ], "limit": 1000, "expand": False, "columns": [ "id", "contract.id", "product_type", "title", "site.address", "site.lat", "site.lng" ] } # List to store all the rows from each page of data all_rows = [] # Make the first request and get the initial page of data print(f'Fetching data from API {API_ENDPOINT}...') response = requests.post(API_URL + API_ENDPOINT, json=json_data, auth=HTTPBasicAuth(USERNAME, PASSWORD)) while response.status_code == 200: data = response.json()['data'] print(f'Got {len(data["rows"])} rows.') # Add the rows from the current page to our total list of rows all_rows.extend(data['rows']) # If there's no 'next' key in the data, then there are no more pages if 'next' not in data or len(data['next']) == 0: break # If there's a 'next' key, then we need to get the next page of data # by including 'after' in our request with the value of 'next' json_data['after'] = data['next'] response = requests.post(API_URL + API_ENDPOINT, json=json_data, auth=HTTPBasicAuth(USERNAME, PASSWORD)) else: print(f'Request failed with status code: {response.status_code}') print (f'Got {len(all_rows)} rows in total.') csv_path = r"C:\NexGenExports\NexGenJobsExport.csv" absolutepath = os.path.abspath(csv_path) print(f'Writing data to CSV file at {absolutepath}...') with open(absolutepath, 'w', newline='', encoding='utf-8') as f: writer = csv.DictWriter(f, fieldnames=all_rows[0].keys()) writer.writeheader() writer.writerows(all_rows) print(f'Data successfully written to {absolutepath}.') # Your Arc Code: # ArcGIS Online credentials username = "removed" password = "removed" # Connect to ArcGIS Online gis = GIS("https://www.arcgis.com", username, password) # Get the feature service item feature_service_item = gis.content.get("635b6b9b19cb4c3e8bdd5b80cbbf8b16") # Get the feature layer from the item feature_layer = feature_service_item.layers[0] # Call the overwrite() method by passing the path to the CSV file feature_layer.overwrite(csv_path) # Clean up the downloaded CSV file os.remove(csv_path) print("CSV file downloaded and appended to the feature service successfully.") However, I get the following error AttributeError Traceback (most recent call last) In [21]: Line 90: feature_layer.overwrite(csv_path) AttributeError: 'FeatureLayer' object has no attribute 'overwrite' All of the code works until the bit where I wish to overwrite to ArcGIS Online. Does anyone know what might be the issue?
gis.stackexchange.com
September 13, 2026 at 3:12 AM
Python AddIns Installation Tool Not Showing After Double Clicking on makeaddin.py
I am using Python Add-In Wizard with ArcGIS 10.4.1 but after getting the files I am not able to create installation Wizard! I tried to create the wizard by double clicking on the looks like something running but No installation file generated at the directory! can you please let me know why this is happening? Update import arcpy import pythonaddins class ButtonClass3(object): """Implementation for ESRI Addin Python_addin.button (Button)""" def __init__(self): self.enabled = True self.checked = False def onClick(self): pass class ComboBoxClass1(object): """Implementation for ESRI Addin Python_addin.combobox (ComboBox)""" def __init__(self): self.items = ["item1", "item2"] self.editable = True self.enabled = True self.dropdownWidth = 'WWWWWW' self.width = 'WWWWWW' def onSelChange(self, selection): pass def onEditChange(self, text): pass def onFocus(self, focused): pass def onEnter(self): pass def refresh(self): pass class ComboBoxClass2(object): """Implementation for ESRI Addin Python_addin.combobox_1 (ComboBox)""" def __init__(self): self.items = ["item1", "item2"] self.editable = True self.enabled = True self.dropdownWidth = 'WWWWWW' self.width = 'WWWWWW' def onSelChange(self, selection): pass def onEditChange(self, text): pass def onFocus(self, focused): pass def onEnter(self): pass def refresh(self): pass
gis.stackexchange.com
September 7, 2026 at 4:08 PM
ArcGIS Pro Runtime Error: the product license has not been initialized
When running scripts that import arcpy, i receive: File ".\Arcpy\PublishService.py", line 9, in import arcpy File "C:\Program Files\ArcGIS\Pro\Resources\ArcPy\arcpy\__init__.py", line 88, in from arcpy.geoprocessing import gp File "C:\Program Files\ArcGIS\Pro\Resources\ArcPy\arcpy\geoprocessing\__init__.py", line 14, in from ._base import * File "C:\Program Files\ArcGIS\Pro\Resources\ArcPy\arcpy\geoprocessing\_base.py", line 14, in import arcgisscripting File "C:\Program Files\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\lib\site-packages\arcgisscripting\__init__.py", line 128, in from ._arcgisscripting import * RuntimeError: **The Product License has not been initialized**. the characteristics of my environment: ArcGIS pro 2.9.3 ArcGIS Pro Named User License The processes were running with out issue, but since yesterday it start with this issue, as it can be seen in the code above, the error is triggered when the script reach the import arcpy command. An special consideration: I have a set of 5-6 scripts that runs over 4 geodatabases, all of them are orchestrated to be run sequentially by a service (the service runs under the same credentials as the ArcGIS Pro application was configured and executed - you know...the profile cookie), but not all the scripts fail, and the failing ones are not always the same. I even have a script made in PowerShell that uses the ArcGIS.Core.Hosting.dll, it is failing too when the initialization is called.
gis.stackexchange.com
September 6, 2026 at 3:14 AM
ArcPy vertices from each polygon and process separately as the input extent of arcpy.EvaluateRules
I used Generate Grid from Area geoprocessing tool to generate a blocklist of polygons. I have the following code for retrieving the vertices from the layer. My goal, to process each feature record separately as the input extent for the geoprocessing tool. Alternatively, If I could use the model builder iteration feature selection to loop through each polygon and pass the extent to the geoprocess "arcpy.EvaluateRules_management" in ArcGIS Pro. Any other ideas? Code below: import arcpy fc = 'C:\\Users\\someuser\\fgdb\\Batch.gdb\\grid_index' fields = ['OID', 'pagenumber', 'SHAPE@'] #infc = arcpy.GetParameterAsText(0) # Enter for loop for each feature for row in arcpy.da.SearchCursor(fc, ["OID@", "SHAPE@"]): # Print the current polygon or polyline's ID print("Feature {}:".format(row[0])) partnum = 0 # Step through each part of the feature for part in row[1]: # Print the part number print("Part {}:".format(partnum)) # Step through each vertex in the feature for pnt in part: if pnt: # Print x,y coordinates of current point print("{}, {}".format(pnt.X, pnt.Y)) else: # If pnt is None, this represents an interior ring print("Interior Ring:") partnum += 1 sample code for the gp tool I need to pass the first four vertices to as the "extent" for each record. # assignlocal variables in_workspace = "https://myserver/server/rest/services/myservicename/FeatureServer" extent = "-113.187897827702 38.0958054854392 -113.142166008849 38.1404599940719" # run the evaluation arcpy.EvaluateRules_management(in_workspace, "VALIDATION_RULES", extent, "ASYNC")
gis.stackexchange.com
September 4, 2026 at 3:11 AM
How to specify field mapping in ArcPy for successive Spatial Joins?
I have a series of spatial joins that I'm performing in a sequence. In total, there will be 9 spatial joins. Each spatial joins has its own field mapping. I created all the fielding mappings for the 9 spatial joins. I followed the field mappings documentation from ArcGIS. Here is a snippet: #initialize field mappings fms = arcpy.FieldMappings() #create field mapping object for all SJ layers fm_bia = arcpy.FieldMap() fm_ward = arcpy.FieldMap() fm_nbh = arcpy.FieldMap() #get field names of all relevant SJ fields f_bia = "AREA_NAME" f_ward = "AREA_NAME" f_nbh = "AREA_NAME" # Add fields to their corresponding FieldMap objects. fm_bia.addInputField(bia, f_bia) fm_ward.addInputField(ward, f_ward) fm_nbh.addInputField(neighbourhood, f_nbh) #create output field mapping bia_field = fm_bia.outputField bia_field.name = 'BIAName' fm_bia.outputField = bia_field ward_field = fm_ward.outputField ward_field.name = 'WardName' fm_ward.outputField = ward_field nbh_field = fm_nbh.outputField nbh_field.name = 'NeigbhbourhoodName' fm_nbh.outputField = nbh_field #add field map objects to FieldMapping object fms.addFieldMap(fm_bia) fms.addFieldMap(fm_ward) fms.addFieldMap(fm_nbh) As you can see, I have added at least 3 objects into the FieldMapping object. In all the examples I have seen, it seems that I just reference the general FieldMapping object, which would be fms in my case. However, when I'm running my spatial joins, how do I specify which field mapping I want the code to use? Do I need to create separate FieldMapping Objects for each spatial join? arcpy.analysis.SpatialJoin(targetFeatures, joinFeatures, outfc, "#", "#", fieldmappings)
gis.stackexchange.com
September 1, 2026 at 5:31 PM