Quantcast
Channel: Forums - Python
Viewing all 2485 articles
Browse latest View live

Python Add-In Edit a Feature Class

$
0
0
I am working on my first Python Add-In and am having a couple issues. What I am trying to do is create a tool that will allow the user to click somewhere on the map and take the map coordinates to create a circle with a predefined radius, fill out some default values, insert it into a SDE feature class, then select the feature to display it's attributes in the attribute editor. This all works pretty well.

The problem is related to editing. I would like for the tool to be disabled if the feature class is not editable or if the layer is not in the current map document. I am also struggling with the edit state. If I start editing and run my tool I get this message: The requested operation is invalid on a closed state. If I make at least one edit, I can run the tool just fine.

Code:

def onMouseDownMap(self, x, y, button, shift):
        mxd = arcpy.mapping.MapDocument('current')
        df = arcpy.mapping.ListDataFrames(mxd, 'Layers')[0]
        fc = ''


        for lyr in arcpy.mapping.ListLayers(mxd,'*', df):
            if lyr.supports("dataSource"):
                lyrSource = lyr.dataSource.split("\\")
                if lyrSource[3] == 'zodiac.GIS.IPCoROW':
                    fc = lyr.dataSource
                    rowLayer = lyr
                    break
        # set the radius of the circle
        radius = 20
        # set the number of sides/vertices the circle will have
        side_count = 40
        # create the degrees for the circle
        degrees = 360 / side_count
        # create a list to hold each vertice point for the circle
        cir_poly = []
        # loop through the number of sides
        for i in range(side_count):
            # set the angle for the current vertice
            angle = (degrees * i) * (math.pi / 180)
            # do some math to set the xFactor and the yFactor
            xFactor = math.sin(angle)
            yFactor = math.cos(angle)
            # set the x and y vertices
            xVal = radius * xFactor + x
            yVal = radius * yFactor + y
            # create a arcpy point
            pnt = arcpy.Point(xVal,yVal)
            # add the point to the list
            cir_poly.append(pnt)
        # create an array and add the list to it
        array = arcpy.Array([cir_poly])
        # create a polygon from the array of points
        polygon = arcpy.Polygon(array)
       
        # set the path to the IPCoROW layer
        #fc = r"Database Connections\Connection to landbaseProd.sde\zodiac.GIS.Land\zodiac.GIS.IPCoROW"
        if len(fc) > 0:
           
            try:
                # create the insert cursor to be used to add our new circle
                print 'Create Insert Cursor'
                with arcpy.da.InsertCursor(fc, ["SHAPE@","OwnerType","ConvType","SOURCE","Comments"]) as c:
                    # insert the circle with attributes into the IPCoROW layer
                    print 'Insert Row'
                    i = c.insertRow([polygon, 'ROW','Easement','DIGITIZED','INSUFFICIENT DATA'])
                    print 'OID =',i
                   
                # refresh the active view to show the new feature
                arcpy.RefreshActiveView()
                print 'Select Features'
                arcpy.SelectLayerByAttribute_management (rowLayer, "NEW_SELECTION", "OBJECTID = " + str(i))


            except Exception, e:
                # if there was an error, print it here
                # common errors include:
                # attempting to edit outside an edit session
                # attempting to edit prior to making any other edits
                print 'Error -', e
            finally:
                pass
        else:
            print 'Could not find zodiac.GIS.IPCoROW'


Issues with updating layers and symbology labels

$
0
0
I am automating a series of maps in Arc 10.1 which involves looping through multiple dataframes replacing/updating layers. Updating the layers has worked fine except for one glitch- the symbology labels don't seem to transfer properly. I had created the layers previously and in some cases had manually changed the labels. For example, for raster where the values were classified as 0-5, 5-20, 20-50, 50-100, 100-167.3 the last range was relabelled ">100". However, when I run the following code the layer is added with the last class labelled 100-167.3 rather than >100. I've double checked all the layers and they have the proper labelling when added manually, just not when scripting with arcpy Do I need to include something to update the labels? Any thoughts would be appreciated!

for df in arcpy.mapping.ListDataFrames(myMXD):

#change layer
lyr2 = arcpy.mapping.ListLayers(myMXD,"",df)[9]
lyr2.replaceDataSource(r"C:\Rasters", "RASTER_WORKSPACE",r"output" + str(spn+1))
sourceLayer = arcpy.mapping.Layer(r"C:\Layers\output" + str(spn+1) +".lyr")
arcpy.mapping.UpdateLayer(df,lyr2,sourceLayer,True)

Help with AddFieldDelimiters in a code block

$
0
0
Hello,

I am trying to do a field calculation using the CalculateField_management tool, which is run on shapefiles, feature classes in gdb, sde etc,. and would like know how to apply the AddFieldDelimiters function into the code block of the tool.

arcpy.CalculateField_management(BenefitArea_Final, "AREA_Ha", "Round ([F_AREA], 1) /10000", "VB", "")

Thanks ~ Rory

Comparing Geodatabase Schema using python

$
0
0
Hi,

Can anybody help me with some suggestions as to how to compare schema of two geodatabases through python scripting? What would be the simplest way to approach for this comparison using python code?

How do you force a GP tool to release it's output

$
0
0
I can see that I get a file lock on the KMZ output file after using MapToKML_conversion while still in the script, or still in Pythonwin. (I can't rename it, delete it etc). 10.1 SP1.
My workflow exports the map to a KMZ and then needs to upzip the file to extract the doc.kml inside.
If I re-run the script without editing I trip up on this file lock.

If I exit Pythonwin something cleans up the lock, so what could I do inside the script?
I have tried a del arcpy without success. Some people have success by encapsulating the tool in a function.
Sometimes an arcpy.RefreshCatalog() works with featureclasses, but in this case it is a system file.

A with... gpTool: would be nice!
Maybe it is just another Annoyance.

currentTime is not supported on this instance of DataFrameTime??????????

$
0
0
Hi,

I keep getting an error in my script tool when trying to prompt the user to specify the time for a dataframe thats properties have not yet been set in the time slider window.

SCRIPT:
import arcpy
mxd = (GetParameterAsText(0))
df = arcpy.mapping.ListDataFrames(mxd)[0]
df.time.currentTime = arcpy.GetParameterAsText (1) #datetime.datetime(2009, 01, 1, 00, 00)
endTime = GetParameterAsText(2) # datetime.datetime(2009, 01, 1, 23, 59)


I need serious help!

interval EsriTimeDelta and modifying the interval????

$
0
0
In the help it says that the timeStepInterval for a layer is read only, and EsriTimeDelta is read only,

Therefore, how can you modify an interval if you cant have write access?

This link:
http://resources.arcgis.com/en/help/...00000023000000

states that currentTime and endTime as well as the interval can be modified.
Is changing the interval really posisble if an interval is already established in a layer and dataframe?

Field Calculator Script Help

$
0
0
The below script works as expected in PythonWin or any other IDE and I am attempting to adapt it to be used in the Field Calculator (ArcMap 10.1) but I am not getting the expected results.

Expected result: populate the field with sequential values that are text/string representation(s) of dates (in the format YYYYMM).

Current result: no errors, but it just populates with a single date/result and not iterating to the next value in the sequence.

Help is appreciated!

Code:


import datetime
from datetime import timedelta
date=0
def jump_by_month(start_date, end_date, month_step=1):
    current_date = start_date
    while current_date < end_date:
    #yield current_date
    carry, new_month = divmod(current_date.month - 1 + month_step, 12)
    new_month += 1
    current_date = current_date.replace(year=current_date.year + carry, month=new_month)
    yr = current_date.year
    strYR = str(yr)
    mo = current_date.month
    if mo < 10:
      strMO = "0" + str(mo)
    else:
      strMO = str(mo)
   
    retVal =  strYR + strMO
    return retVal


Force the output of a tool to use a built in color ramp

$
0
0
Hello everyone,

I am wondering if it is possible to force the output of a tool to use a specific color ramp using python code. I downloaded a tool that automatically creates filled contours from DEM's at intervals that I specify. The code is written to look for a symbology layer to use for the symbology of the output but I am looking for a way to set the symbology to a specific color ramp without using a symbology layer. I have been digging through the forums but have not come across anything that addresses my question directly. Thank you in advance for any information you have.

Thanks,

-Jason

"python.exe has stopped working" on raster.save

$
0
0
I am attempting to perform raster calculations with in-memory rasters in a script using arcpy (ArcMap v10.0). I get this error from multiple different inputs and it occurs from multiple different areas in my code depending on slight modifications.

The basic workflow is this:
  • load in a raster using arcpy.sa.Raster
  • perform a raster calculation
  • save the raster using raster.save (this is where the error occurs)

For example, I have

Code:

# make a raster from the bounding region
result = arcpy.PolygonToRaster_conversion(boundingRegion, vField, outputRegion, '', '', cellSize)
outputRaster = arcpy.sa.Raster(outputRegion)
outputRaster.save('C:/temp/temprast.tif') # no error occurs
       
# convert any NoData to "outside" the output region
outputRaster = arcpy.sa.Con(arcpy.sa.IsNull(outputRaster), rastOutVal, rastInVal)
outputRaster.save('C:/temp/temprast.tif') # python crashes with a pop-up window and windows error "python.exe has stopped working"

Sometimes saving the raster has no ill effect. And saving the raster to a different filename (e.g. C:/temp/temprast2.tif) for consecutive calculations also averts the crash. However, the crash that I am concerned about happens when I attempt to save the raster only once and do so at the end of several raster calculations.

I have a couple guesses as to what may be causing the crash.

1) arcpy attempts to write the file before the raster calculation is complete. I dont think this is the case. I have put in a sleep command for 10 seconds, which should be plenty of time. Arcpy would also have to be creating a sub-process that can run behind the main process, which I dont think is happening.

2) arcpy attempts to save a raster with no information or incompatible information that has been produced during calculations. I dont think this is the case, because I can get an output file saved if I save all the intermediate rasters to files before the final one. So unless writing each intermediate raster to a file somehow makes the information compatible with future calculations, this cant be it.

3) In attempting to save the in-memory raster to the hard drive, arcpy is attempting to access/overwrite the same RAM that is currently occupied by the in-memory raster. I dont have a way to test this.

Any suggestions would be a huge help. One boon of arcpy in v10.x is the ability to perform raster calculations in-memory. The only solution I can come up with (save all intermediate rasters as separate files) takes away this advantage.

I've attached a sub-section of the problem script. I cant attach the whole thing because it is part of a package I hope to release in the near future.

UPDATE: I have just discovered another curious way to avoid the problem I was having.
1) If I put in a breakpoint (import pdb; pdb.set_trace) just before the spot where the final raster is to be saved to disk, and
2) then call a different temporary raster that is stored in memory (i.e. >> raster), and finally
3) call the output raster (i.e. >> outputRaster)

then the problem does not happen. The mechanism that seems to be at work here is that when the temporary rasters are accessed in Python (by me), they are written to the hard disk (confirmed by watching files in the temporary directory). This subsequently means all arcpy has to do when the outputRaster.save command is called is change the name/copy the temporary raster to its permanent location.

However, this does not solve my problem! If I try something like ">> print raster" without the break statement, I get the same crash. For some reason I need to be interactively calling the rasters for them to be written to the hard disk.

It also appears the the output raster is wrong with this method.

Hopefully it gives some additional helpful information.

UPDATE 2: Doing the same thing in UPDATE 1, but putting the breakpoint at the beginning of the raster calculations seems to solve the problem of the output being false. I guess there's an issue with raster calculations in memory.
Attached Files

Batch clip using arcpy script

$
0
0
Hi, I am a GIS student, just starting out with python, and I am working on a project in which I want to create a custom script tool to clip a list of feature classes in a municipality to a single clip feature representing flood extent (FloodLevel). Can I create a list of the feature classes and then loop through the list to accomplish this? Here is what I am trying, though I cannot get the script to work at this point. I get an error that says: 'list' object is not callable. And I am not sure how to properly provide the output name for multiple features at once.


# Clip town features to a flood level polygon
# Define input parameter for floodLevel polygon
# Define infrastructure variables

FloodLevel = arcpy.GetParameterAsText(0)
FC1 = "Town_Boundary"
FC2 = "Parcels_2010"
FC3 = "Buildings_2009"
FC4 = "Trails"
FC5 = "Banff_Roads"
FC6 = "Water_Main"
FC7 = "Storm_Main"
FC8 = "Hydrant"

# Create list of feature classes and loop through the feature classes
Features = [FC1, FC2, FC3, FC4, FC5, FC6, FC7, FC8]

# Clip features in list to the FloodLevel polygon feature
for items in Features():
arcpy.Clip_analysis(Features, FloodLevel, "Features_clip")

Any suggestions on how I could solve this scenario would be helpful!
Thanks,
Myla-Rae

can't export correct images using script tool, works fine in regular script

$
0
0
Hi,

I am having trouble getting my script tool to export the currentTime and endTime with a hard coded interval of 1 hours.

It works fine in my regular script without parameters but when I set the below code the images arent exported

mxd= (GetParameterAsText(0))
currentTime = GetParameter(1)
endTime = GetParameter(2)

In the script tool the data type is set to date. I'm not sure what the problem is. The user can specify the date and time in the script tool but after the tool runs and is complete the exported images have not been interated correctly with the specified hard coded 1 hour interval.

Any help?

Thank you

Python png export not including table on layout

$
0
0
Hello all,

I have a layout that includes a table (created within ArcMap through a attribute table) and I am trying to export it as a png. However, when I try to export it through python, it doesn't include the table (the map and all other elements are there).

I have tried making a separate python code just for those 2 lines, trying ExportToJPEG, and ExportToPDF.

However, when I open up the mxd and use the same exact code in the python window within Arc - it magically exports correctly.

Has anyone else had this issue? (Using 10.0)

Creating serial graphs with arcpy

$
0
0
Hello,
I need to make export reports with graphs. One map and one graph for each selected feature in a loop. When I add the graph to the layout and set the graph so that it only shows the values of the selected features it doesn't update when a new feature is selected with arcpy. Also setting the graph to show all values and making a query that only the selected feature is shown, doesn't work. Still the graph doesn't update. Embedding the graph to the layout of the map would be my favourite.
My second unsuccessful try was to select features and export the resulting graph with SaveGraph_management, but here I experienced the same problem.
When I select features manuelly/write a definition query manually the graph updates.
I would be really happy if you could help me, I've been trying to solve this problem for quite a few hours.
Thanks,
Pedol

Zoom to user-defined extent

$
0
0
Hello all,

I am working on something that I think is pretty simple but it seems to be evading me at this time. I have a layer "Counties" and want the user to pick a County using sys.argv and then have the map set that county as the data frame extent. The Counties layer has the county name in the NAME field.

Here is the code I am using:

#Import modules
import os
import sys
import arcpy

#Set Map Document
mxd = arcpy.mapping.MapDocument("Current")

#Set Overwrite Option
arcpy.env.overwriteOutput = True

#Sets parameters (attributes)
CountyName = sys.argv[1]

#Gets Name value for definition query
rows = arcpy.SearchCursor("TexasCounties")
for row in rows:
DefQuery= row.getValue("NAME")

#Set String Values for Definition Query
strName_DQ = "NAME = '" + DefQuery + "'"

df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
lyr = arcpy.mapping.ListLayers(mxd, "TexasCounties", df)[0]
lyr.definitionQuery = strName_DQ
df.extent = lyr.getSelectedExtent()

del row
del rows

#Refresh Map to refelct Changes
arcpy.RefreshActiveView()
mxd.save()

del mxd,

Any help y'all could priovide would be appreciated.
Thanks.

arcpy.mapping.ListLayoutElements which element type to use?

$
0
0
I have a series of mxds that I have previously constructed which contain text elements and picture elements grouped. Their position within each mxd differs slightly. I would like to standardize the position of tese groups of text and objects/pictures. What element_type do I need to use?

Calculate Field problem Please Help

$
0
0
Hi,

I've written a script that narrows down a selection of points (cities) and then adds a field called CITYNAME to the feature class. I need to update the new CITYNAME field with the same values as the NAME field in the same feature class but it doesn't update them although it shows as having run successfully.

I need to do this so that I can spatially join this points (cities) dataset to polygons (counties) and lines (roads) because all three of them have the same fieldname called NAME.

I'm using ArcGIS v10.0 and any help would be appreciated as I've tried various methods like CalculateField and UpdateCursor to no avail.

Thanks,

Scotaidh

Code:

# ExtractFeaturesByLocationAndAttribute.py EFLA.py
# Description: Extract features to a new feature class based on a Location and an attribute query
# then add field called CITYNAME and update it with the NAME field from the cities layer

# import system modules
import arcpy
from arcpy import env
import os

# set overwrite option
arcpy.env.overwriteOutput = True

# Put in error trapping in case an error occurs when running tool
try:
    # Make a layer from the cities feature class
    arcpy.MakeFeatureLayer_management("H:/working/Findsites.gdb/cities","citiesL")

    # Select all cities that are within 30km of an interstate
    arcpy.SelectLayerByLocation_management("citiesL", "WITHIN_A_DISTANCE", "H:/working/Findsites.gdb/interstates", "30 KILOMETERS", "NEW_SELECTION")

    # Within the selection (done above) further select only those cities that have a university and low crime rate
    arcpy.SelectLayerByAttribute_management("citiesL", "SUBSET_SELECTION", "UNIVERSITY = 1 AND CRIME_INDE <= 0.02")
   
    # Make a layer from the counties feature class
    arcpy.MakeFeatureLayer_management("H://working/Findsites.gdb/counties","countiesL")
   
    # From the counties layer select only those counties with a large enough workforce and number of farms
    arcpy.SelectLayerByAttribute_management("countiesL", "NEW_SELECTION", "AGE_18_64 >= 25000 AND NO_FARMS87 >= 500")

    # Select all cities that intersect counties that meet work force and number of farms criteria
    arcpy.SelectLayerByLocation_management("citiesL", "INTERSECT", "countiesL", "", "SUBSET_SELECTION")
   
    # Write the selected features to a new featureclass
    arcpy.CopyFeatures_management("citiesL", "H:/working/Findsites.gdb/CityList")
   
    # create a new field called CITYNAME to replace NAME because other datasets have a NAME field
    arcpy.AddField_management("H:/working/Findsites.gdb/CityList", "CITYNAME", "TEXT", "", "", "25")
   
    expression1 = '!MP_VAL!'
    arcpy.CalculateField_management(CityList, CITYNAME, expression1, "PYTHON", "")
   
    #Calculate Field - update new CITYNAME field with NAME field
    # arcpy.AddMessage("Calculating Updated Field...")
    # Expression = "'{0}'".format(arcpy.GetValue(NAME))
    # single quoted string literal
    # arcpy.CalculateField_management(CityList, CITYNAME, Expression, "PYTHON")
   
except:
    # If an error occurred print the message to the screen
    print arcpy.GetMessages()

Create Tin with multiple input features

$
0
0
This piece of code works just fine in my script and the TIN is output with no problems
Code:

arcpy.CreateTin_3d(TIN_name, coordsys, outputFC + " Shape.Z masspoints", Delaunay)
However, when I try to add my second input feature my code will not run
Code:

arcpy.CreateTin_3d(TIN_name, coordsys, outputFC + " Shape.Z masspoints" ; waterPoly + " Shape.Z softerase", Delaunay)
This is the code that I get when I export a script from ModelBuilder. However, these are hard coded shapefiles that
Code:

arcpy.CreateTin_3d(Output_TIN, "", "test Shape.Z masspoints <None>;test_3d_polys Shape.Z softerase <None>", "DELAUNAY")
This doesn't work either
Code:

arcpy.CreateTin_3d(TIN_name, coordsys, [outputFC + " Shape.Z masspoints"; waterPoly + " Shape.Z softerase"], Delaunay)

Accessing same python script from multiple toolbox at same time

$
0
0
All,

I have parked scripts in one location . And Multiple toolboxes are referenced to same python script file ..

If the multiple users using different toolbox run the same tool (which is referencing same python script)in the same time . Will there be a problem ?

Writing data from feature class to delimited text file

$
0
0
I have several feature classes with values that I would like to export to a tilda (~) delimited text file using a Python script. My customer says tildas are the easiest delimiters for him to work with. I found the csv.writer module available in Python and it was working perfectly when I was only exporting 6 fields of data. However, when I added another 6 fields of data to the export, the script began to crash, giving me the error "IOError: [Errno 22] Invalid argument." After a lot of searching on the web, I've figured out this is an issue with Windows, not Python, and appears to be related to this article (http://support.microsoft.com/default...b;en-us;899149). The feature class is about 375Mb. I've already tried adjusting the csv.writer to open the file as "w+b," as the article suggests, but that didn't make a difference. What's weird is there's no consistency when the error pops up. Sometimes all of the files are written successfully, sometimes the script crashes after writing a few lines to teh first file, and literally anywhere in between.

I'm at a loss on how to solve this. I'm still pretty new to Python and feel like maybe there's a way to break up the data so it only X number of megabytes of data at a time. However, I don't know how to do that or even how to determine how small to break of the files. The article mentions a 64Mb limit but, as I said, I've seen the script crash after a few lines are written to the first file (i.e. far less than 64Mb of data). Any help would be greatly appreciated. FYI, I'm running this script on a Windows Server 2008 R2 OS. Below is my code.

Code:

# ConvertFCtoTXT.py
# Created on: March 20, 2013
# Description: Converts DCYF/OLCR geocoded feature classes to tilda-delimited text files.
# Notes: Logging module requires this script be called through the DCYF-OLCR Daily Geocode Batch.py script.
# ---------------------------------------------------------------------------------------------------------------

import arcpy, csv, logging
from arcpy import env

#Set up variables
env.workspace = "C:\\Daily Geocode Processes\\DCYF OLCR Daily Geocode\\Workspace\\Workspace GDB.gdb\\GeocodedFeatures"
ProjectGDB = "C:\\Daily Geocode Processes\\DCYF OLCR Daily Geocode\\Workspace\\Workspace GDB.gdb\\GeocodedFeatures"
CubeWorkspace = "\\\\cubed03\\Geocoding"

# Log start date/time.
logging.info("Started ConvertFCtoTXT.py.")

# Create iterator to run process for each feature class in WorkspaceGDB.
for fc in arcpy.ListFeatureClasses():
  InputFC = ProjectGDB + "\\" + fc
  OutputTXT = CubeWorkspace + "\\" + fc.rstrip("_GC") + ".txt"

  # Module defines get_fields function. Allows writerow to iterate through each row in the table.
  # Yield iterates through each row, without storing the rows in memory.  Yield stops when no more records exist.
  def get_fields(InputFC, Fields):
      with arcpy.da.SearchCursor(InputFC, Fields) as cursor:
        for row in cursor:
            yield row

  # Describe opens the feature class properties, including the field names, to function
  DescribeFC = arcpy.Describe(InputFC)

  # Selects only the fields necessary to export
  FieldNames = [field.name for field in DescribeFC.fields if field.name
                in ["Key", "GCAcc", "Address_Std", "City_Std", "State_Std", "ZIPCode_Std", "County_Std", "X_Coordinate", "Y_Coordinate"]]

  # Defines rows using the get_fields function (see above)
  rows = get_fields(InputFC, FieldNames)

  # Opens the output file, prepares it to write as ~ delimited, and writes the headers and rows to the table
  with open(OutputTXT,'w+') as out_file:
      out_writer = csv.writer(out_file, delimiter="~")
      out_writer.writerow(FieldNames) #writes the headers to the file
      for row in rows:
        out_writer.writerow(row) #writes the rows to the file

  del row
  del rows
  out_file.close()
  print OutputTXT + " done"

del fc

# Log completion date/time
logging.info("Completed ConvertFCtoTXT.py.")

Viewing all 2485 articles
Browse latest View live