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

in_memory workspace bug

$
0
0
I posted this comment here but wanted to start a new thread, since this seems like a clear bug & I'd be interested if anyone else has come across it or found a solution.

I have a script that ranks the values in a field and writes the ranks (e.g largest = 1, smallest = n or vice versa) to another field. When I do this on a FC stored in a fileGDB I get accurate results. However, if I switch to the in-memory workspace, the rank values are sequential with the OBJECTIDs. Can anyone replicate this, have similar problems, or know a workaround?

Code:

import arcpy
import sys

#Function to rank the values of a field write the rank to an existing field.
#Arguments include workspace path (workspace), FeatureClass name (FeatureClass), field with values to rank (valueField),
#and field to write values to (RankField).
#Order can be either ascending "A" (smallest value rank=1) or descending "D" (largest value rank =1)
#
class Rank:
        def __init__(self, workspace, FeatureClass, ValueField, RankField, Order):
                self.workspace = workspace
                self.fc = FeatureClass
                self.valueField = ValueField
                self.rankField = RankField
                self.Order = Order

        def rank(self):
                try:
                        arcpy.env.workspace = self.workspace
                        currRank = 0
                        lastRank = 0
                        lastVal = None

                        #Since arcpy.da takes "ASC" and "DESC" instead of "A" and "D", reassign values if needed
                        if self.Order == "A" or self.Order == "ASC":
                                self.Order = "ASC"
                        elif self.Order =="D" or self.Order == "DESC":
                                self.Order = "DESC"
                        else:
                                arcpy.AddError('Sort order was not recognized.  Use "A" for ascending or "D" for descending.')
                                print('Sort order was not recognized.  Use "A" for ascending or "D" for descending.')
                                sys.exit()

                        #****************************************************
                        #arcpy.da version of rank script
                        #****************************************************
                        fields = (self.valueField, self.rankField)

                        #sql_clause is a named parameter (don't need to add None values for other optional params.  ORDER BY sorts the ranking
                        with arcpy.da.UpdateCursor(self.fc, fields, sql_clause=(None, 'ORDER BY {} {}'.format(self.valueField, self.Order))) as rows:
                                for row in rows:
                                        currVal = row[0]
                                        if currVal != lastVal:                  #if the current value does not equal the previous value
                                                currRank += 1
                                                row[1] = currRank
                                        elif currVal == lastVal:
                                                row[1] = currRank
                                        else:
                                                print "Unexpected occurance"
                                        lastVal = currVal
                                        rows.updateRow(row)
                                print "Finished rank script"

                except Exception as e:
                        arcpy.AddError("The was a problem with the Rank Module... " + e.message)
                        print("The was a problem with the Rank Module... " + e.message)
                        sys.exit()


Python Toolbox Raster Parameter Error

$
0
0
Hey all, I borrowed a simple script I found online to clip a shapefile from the extent of a raster. It works perfectly from the ArcMap built in python command prompt. I modified is slightly to use in a tool. It's having issues accepting the raster (inraster) in:
Code:

extent = arcpy.Raster(inRaster).extent
I get the following error:

Quote:

extent = arcpy.Raster(inRaster).extent
TypeError: expected a raster or layer name
I'm using "Raster Layer" as my inRaster parameter type. The raster type I am using is an ERDAS IMAGINE .img file. I'm thinking it must be conflicting with the parameter type and the .img input raster, but I can't figure out what it is. As I mentioned, it worked from the command prompt, just not in the tool. Any suggestions are welcome.

Code is as follows:

Code:

import arcpy

inLines = arcpy.GetParameter(0)
inRaster = arcpy.GetParameter(1)
outRaster = arcpy.GetParameter(2)

pnt_array = arcpy.Array()
extent = arcpy.Raster(inRaster).extent
pnt_array.add(extent.lowerLeft)
pnt_array.add(extent.lowerRight)
pnt_array.add(extent.upperRight)
pnt_array.add(extent.upperLeft)

poly = arcpy.Polygon(pnt_array)

arcpy.Clip_analysis(inLines, poly, outRaster)

Thanks,
Mike

Loop raster dataset in Python

$
0
0
Hi,
I am very new to Python and I want to extract raster by mask for a number of images. I am attempting to write python code for this and incorporate a loop so it will process every raster image within the folder without me manually changing it. This is my code below but it does not work. From the #Loop through list of rasters sections i.e. rasters.reset() all the errors begin to occur. Can someone please help me fix this coding.


# Import system modules
import arcpy
from arcpy import env
from arcpy.sa import *

# Set environment settings
env.workspace = "J:\PhD\Vegetation\MODIS13Q1\MODIS_NDVI_z56"

# Set local variables
inRaster = "J:\MODIS"
inMaskData = "arcreproarea.shp"
outRaster = "J:\\MODIS"

# Check out the ArcGIS Spatial Analyst extension license
arcpy.CheckOutExtension("Spatial")

# Get a list of the rasters in the workspace
rasters = arcpy.ListRasters()
rasters

# Loop through the list of rasters
rasters.reset()
raster = rasters.next()

while raster:
# Set the outputname for each output to be the same as the input
output = out_workspace + raster


# Process: Extract by Mask
arcpy.gp.ExtractByMask_sa(inRaster, inMaskData, outRaster)


# Loop
raster = rasters.next()


Thanks,
Jess

selecting with sqlite?

$
0
0
hi all; apologies if this has been answered already elsewhere, please point me in that direction if so...

python novice here, and learning arcgis after having come from a mapinfo background....

I would like to, in arc 9.3 (alas not 10), use sql to select some records from a table, in order etc. here is my python so far:

from easygui import *
import arcgisscripting
import re
import dbfpy
from dbfpy import dbf
import sqlite3
import os

# create the geoprocessor object
gp = arcgisscripting.create(9.3)

inWorkspace = enterbox(msg="please enter your working directory",title="working directory")
layer1 = fileopenbox(default=inWorkspace+"\*.shp")
layer2 = fileopenbox(default=inWorkspace+"\*.shp")

print layer1
print layer2
print inWorkspace

gp.workspace = inWorkspace
# process
gp.PointDistance_analysis(layer1,layer2,"temp.dbf","#")

gp.Rename_management("temp.dbf", "output.dbf")

db = dbf.Dbf(gp.workspace+"\output.dbf")

records = db.sql("select * where distance > 0.6")


...this last line is where I'm stuck of course ('distance' is a valid column in the dbf); syntax for using sql on a dbf I've just made??? I'm so used to just using plain old sql in the command line in mapinfo, but of course esri must have a similar tool, just a matter of figuring it out...

thanks all,

cj

Python script for field table

$
0
0
Hi everyone,
I have been working on a project for a while now. I have created more than 2,000 point file so far but, I realize that I needed to add a field name "Section". On the "Section" field I'll have "D-60" from top to bottom. When I use the field calculator it only shows "-60" but not "D-60" which is the one I want see throughout the field. Is there a Python script I can use to perform this task? I'm currently using ArcGIS 10.0

Best regards,
Rudy Charlot

Python crashes running stand alone script, composite locator, AGS 10.1 SP1 desktop

$
0
0
I have a Python script with a composite locator that works when run from the Python window in ArcMap, but crashes when run standalone. I am running ArcGIS 10.1 SP1 (Build 3143) Desktop Standard(ArcEditor) on a Windows 7 64 bit. Also I can run the script in the Python window in ArcMap or standalone if I change the locator to a individual locator. The locators are from StreetMap Premium 2012 R3 - USA_2012R3_NT_AddressPoint' and 'USA_2012R3_NT_Composite' .

The message Windows message from the crash is:

Description:
Stopped working

Problem signature:
Problem Event Name: APPCRASH
Application Name: python.exe
Application Version: 0.0.0.0
Application Timestamp: 4df4ba7c
Fault Module Name: Geocoding.dll
Fault Module Version: 10.1.1.3143
Fault Module Timestamp: 5058d4a0
Exception Code: c0000005
Exception Offset: 000a58be
OS Version: 6.1.7601.2.1.0.256.48
Locale ID: 1033

It appears that the problem is with running a composite locator as a standalone Python script.

Thanks,
Jeff

Problems with MakeQueryTable_management in code

$
0
0
I am having trouble getting the code below to execute succesfully:

Code:

import arcpy

tableList = ['Database Connections\\Metering_Data.odc\\tblFlowMeters', \
            'Database Connections\\Metering_Data.odc\\tblDataCollectionPeriods', \
            'Database Connections\\Metering_Data.odc\\tblFlowMeterDataCollectionPeriods', \
            'Database Connections\\Metering_Data.odc\\tblMeteringData']

fieldList = [['tblFlowMeters.MeterName'], ['tblDataCollectionPeriods.StartDate', \
              'tblDataCollectionPeriods.EndDate'], ['tblMeteringData.MeteringDataId', \
              'tblMeteringData.MeteringDateTime', 'tblMeteringData.DepthInches', \
              'tblMeteringData.VelocityFTperSec', 'tblMeteringData.FlowMGD', \
              'tblMeteringData.RainInches','tblMeteringData.DebrisInches']]

whereClause = "(tblFlowMeters.FlowMeterId = tblFlowMeterDataCollectionPeriods.FlowMeterId \
              AND tblFlowMeterDataCollectionPeriods.DataCollectionPeriodsId =  \
              tblDataCollectionPeriods.DataCollectionPeriodsId AND \
              tblDataCollectionPeriods.DataCollectionPeriodsId = \
              tblMeteringData.DataCollectionPeriodId AND \
              tblFlowMeterDataCollectionPeriods.FlowMeterIdDataCollectionPeriodsId \
              = tblMeteringData.FlowMeterDataCollectionPeriodsId ) AND \
              (tblFlowMeters.MeterName = 'RH2A')"

arcpy.MakeQueryTable_management(tableList, "tblFlowMetersTest7", "USE_KEY_FIELDS", "tblMeteringData.MeteringDataId", fieldList, whereClause)

I get the following error message when I run it:
Code:

Traceback (most recent call last):
  File "<string>", line 73, in execInThread
  File "C:\Program Files\PyScripter\Lib\rpyc.zip\rpyc\core\netref.py", line 196, in __call__
  File "C:\Program Files\PyScripter\Lib\rpyc.zip\rpyc\core\netref.py", line 71, in syncreq
  File "C:\Program Files\PyScripter\Lib\rpyc.zip\rpyc\core\protocol.py", line 431, in sync_request
  File "C:\Program Files\PyScripter\Lib\rpyc.zip\rpyc\core\protocol.py", line 379, in serve
  File "C:\Program Files\PyScripter\Lib\rpyc.zip\rpyc\core\protocol.py", line 337, in _recv
  File "C:\Program Files\PyScripter\Lib\rpyc.zip\rpyc\core\channel.py", line 50, in recv
  File "C:\Program Files\PyScripter\Lib\rpyc.zip\rpyc\core\stream.py", line 166, in read
EOFError: [Errno 10054] An existing connection was forcibly closed by the remote host

If I run the code without the fieldList variable, the code runs succesfully. Is there something wrong with my fieldList variable that I am not seeing?

I can run the MakeQueryTable_managment toolbox in ArcMap with all the same values successfully. It also runs if I do it via a model. When I export the model to a script it also runs successfully.

Anyone have an idea why my fieldList variable wont' allow it to run?

Python Add-In help please

$
0
0
I am struggling to get this working. Attempting to follow along with Creating an addin tool

http://resources.arcgis.com/en/help/...000001q000000/

So, I have made it through Step 3 (and maybe my edits are not sticking or something, not sure). Keeping things very simple, I just want to display a message box when the tool is clicked.

Code:


def onRectangle(self, rectangle_geometry):
    pythonaddins.MessageBox("Add-In executed!")

However, moving on to "Testing an add-in" http://resources.arcgis.com/en/help/...0000026000000/

Step 2. does not work as epected. I double-click the new .esriaddin file that was created and it asks me which program to use to open it. Obviously, I don't know what to choose as it is just supposed to be some sort of ESRI dialog (per the Step 2. in the doc/link above).

So, ok -- I'll just run this in PythonWin.

It runs, but it does not create the expected GUID folder, nor does it copy the contents to the folder Documents\ArcGIS\AddIns\Desktop10.1.


Any help?
Thanks,
j

Alternative to replication for copying features in SDE?

$
0
0
We need to replicate data from SDE 10.0 to SDE 9.2, which is not possible using replicas due to all the changes between versions 9.2 and 10. I know of at least one case where someone is doing this very thing using Python, but I unfortunately do not have access to their script and have no idea how they're doing it.

Basically, they are copying a featureclass from SDE 10 to SDE 9.2, while SDE 9.2 is running and also while that featureclass is being accessed in the 9.2 SDE. I have tried a few options to do this and always run into locks on the 9.2 featureclass since it is currently in use by other users/applications. We pretty much need to do what a replica does: synchronize changes (adds/deletes/modifications) in the featureclass between the two databases without having to stop the database or block access to the featureclass.

How would you go about accomplishing this in Python? I have searched through the geoprocessing documentation and simply cannot figure out how to do this. All of my searches lead back to replication, but again, creating a replica that will move data from SDE 10 to SDE 9.2 is not possible.

Any and all ideas would be most appreciated!

Get value of a specific location from TIN

$
0
0
Hello,

I'm looking for something similar to arcpy.GetCellValue_management, but for TINs instead of rasters. The idea behind it is that I'd like to be able to read terrain Z coordinate from both rasters and TINs - whatever the user chooses. The relevant part of the code is as follows:
Code:

def readZ(dataset,x,y):
    desc = arcpy.Describe(dataset)
    if desc.datasetType == "RasterDataset":
        result = arcpy.GetCellValue_management(dataset,str(x) + " " + str(y))
        return result.getOutput(0)
    if desc.datasetType == "Tin":
        #return what is the Z value of tin dataset in location x,y
        #what goes here?
    return None #neither raster nor tin

I searched with google but apparently I ask the wrong questions. I have only Spatial Analyst from extensions, so no other extensions available (3D analyst in particular).

Cheers
t.wilk

Generate random numbers with known occurence possibilities

$
0
0
Hallo!

I would like to generate random triads of numbers (h, v, d).

The d number is generated according to the generated values of h, v following some if statements

h and v are integers within a known interval

For example if h=1 and v=2 ... d can take the value 1 (with possibility 83.3%) or 2 (6.7 %) or 3 (10 % possibility).

How can I declare these possibilities in Python???

Trouble with UpdateCursor.updateRow()

$
0
0
I am trying to update an SDE feature class based on another SDE feature class using an Update Cursor. Th feature classes have identical fields and the same number of records. There is a "LASTMODIFIED" date field that is changed anytime a record is updated in the source feature class.

What I'm doing is matching up the rows in each table using their "ID" field, then checking to see if the "LASTMODIFIED" date is different. If it is different, then I want to update the entire row of the target feature class with the row from the source feature class.

For some reason, this is not working. The script runs without error, and I've inserted counters to make sure it is finding cases where the last modified dates are different (it is). However, when I check the records of the target dataset after the script has run, no data has been changed at all.

Does anyone know why this is happening? I want the entire record to be replaced with the source FCC record, and I thought updateRow() would do that. The only other thing I can think of is to delete the existing record and insert the record I want in its place, but that seems kind of stupid to me.

Code:

sourceFCCur = arcpy.UpdateCursor(SourceFCPath)
for sourceFCRow in sourceFCCur:
    targetFCCur = arcpy.UpdateCursor(TargetFCPath)
    for targetFCRow in targetFCCur:
        if targetFCRow.ID == sourceFCRow.ID:
            sourceFCDate = sourceFCRow.getValue('LASTMODIFIED')
            targetFCDate = targetFCRow.getValue('LASTMODIFIED')
            if sourceFCDate != targetFCDate:
                targetFCCur.updateRow(targetFCRow)
    del targetFCCur

ReProject Error In Script

$
0
0
At the end of a script I run a Projection, but I keep getting the following Error

PYTHON ERRORS:
Traceback info:
File "G:\Scripts\BARRIER_MERGE_edits.py", line 48, in <module>
arcpy.Project_management(GRADIENT_BAR_PT, GRADIENT_BARH83, outCS, CSTRANS)

Error Info:
ERROR 000622: Failed to execute (Project). Parameters are not valid.
ERROR 000628: Cannot set input into parameter out_coor_system.


Here is a piece of the script and the defined variables:

Code:

outCS = "NAD_1983_HARN_StatePlane_Washington_South_FIPS_4602_Feet"
CSTRANS = '"NAD_1927_To_NAD_1983_NADCON", "NAD_1983_To_HARN_WA_OR"'

arcpy.Project_management(GRADIENT_BAR_PT, GRADIENT_BARH83, outCS, CSTRANS)

Any ideas on where I am going wrong here? I appreciate the help!!

Looping the "Resample" operation

$
0
0
I am trying to resample multiple rasters with the "Resample_management" ArcPy function.

The code below works perfectly:

Code:

import arcpy
from arcpy import sa
arcpy.gp.overwriteOutput=True
arcpy.CheckOutExtension("spatial")
import glob

Input=glob.glob("D:\Freelancer\oDesk\Create-ArcPy-Scripts\TestFiles\*tif")

for i in Input:
    arcpy.Resample_management(i, i+"_1000.tif", "1000 1000", "BILINEAR")

But it saves the output files in the same directory with the input ones. To change this, I modified it a bit.

Code:

import arcpy
from arcpy import sa
arcpy.gp.overwriteOutput=True
arcpy.CheckOutExtension("spatial")
import glob

Output="D:/Freelancer/oDesk/Create-ArcPy-Scripts/OutputFiles/"
Input=glob.glob("D:/Freelancer/oDesk/Create-ArcPy-Scripts/TestFiles/*tif")

for i in Input:
    arcpy.Resample_management(i, "'D:/Freelancer/oDesk/Create-ArcPy-Scripts/OutputFiles/%s_1000.tif' % i", "1000 1000", "BILINEAR")

But this throws an error:

Code:

Traceback (most recent call last):
  File "D:\Freelancer\oDesk\Create-ArcPy-Scripts\testscript-2.py", line 11, in <module>
    arcpy.Resample_management(i, "'D:/Freelancer/oDesk/Create-ArcPy-Scripts/OutputFiles/%s_1000.tif' % i", "1000 1000", "BILINEAR")
  File "C:\Program Files (x86)\ArcGIS\Desktop10.1\arcpy\arcpy\management.py", line 12407, in Resample
    raise e
ExecuteError: ERROR 999999: Error executing function.
Failed to execute (Resample).

What am I doing wrong?

arcpy.da cursors and layer definition query

$
0
0
In my mxd I found that if I ran an arcpy.da search cursor with a where clause on a layer that had a definition query applied to it, that the where clause would not be honored. Anybody else have this problem?

Thanks
George

Select Layer By Attribute User Input problem - Please help

$
0
0
Hi,

I'm writing a script for a toolbox that gets user input to run a select layer by attribute and location tool on a cities shapefile that contains two fields of interest, cime index (CRIME_IND) and university status (UNIVERSITY), both integers. The 1st part, select layer by attribute, results in a layer being saved (citiesL) with those attributes and is shown in the code below.

I'm having problems in getting the user to define which attributes to select, none, one or more than one. If the user chooses to select only crime attributes ("CRIME_INDE" <= 0.02) then only those ones would be saved and if the user chooses to select crime and university status attributes ("CRIME_INDE" <=0.02 AND "UNIVERSITY" = 1) then both those sets of attributes would be saved to the layer file.

Similarily, if the user does not fill in the required fields (by changing their default to nothing) then all the attributes of the cities layer would be effectively be saved to the layer file i.e. no selection by attribute.

When I run the code in the toolbox it completes successfuly but no layer is saved (citiesL). I'm not sure where I'm going wrong with this and would appreciate any help.

Thanks

scottaidh

Code:

# script for user input tool based on select layer by location and attribute
# parameters within feature classes are optional
# scottaidh 8/4/13

# import system modules
import arcpy, os, traceback, arcpy
from arcpy import env
arcpy.env.overwriteOutput = True

# get user supplied path, layers and fields
path = arcpy.GetParameterAsText(0)

try :
        citiesFC = arcpy.GetParameterAsText(1) # cities Layer is cities Feature Layer
        crimefieldindex = arcpy.GetParameterAsText(2) # crime index is CRIME_INDE and is a Double integer
        whereClause1 = "{0} = '{1}'".format(arcpy.AddFieldDelimiters(citiesL, crimeField), crimefieldindex)
        crimeField = arcpy.GetParameterAsText(3) # crimeField is fieldname 'CRIME_INDE' SQL expression
        universityfieldindex = arcpy.GetParameterAsText(4) # universityfieldindex is the UNIVERSITY field and is DOUBLE integer
        whereClause2 = "{0} = '{1}'".format(arcpy.AddFieldDelimiters(citiesL, universityField), universityfieldindex)
        universityField = arcpy.GetParameterAsText(5) # universityField is fieldname 'UNIVERSITY' SQL expression
        outputlayer = arcpy.GetParameterAsText(6) # output layer name
       
        # make a layer from the cities feature class
        arcpy.MakeFeatureLayer_management(citiesFC, "citiesL")
       
        # select the attributes from citiesL from user input
        prj = ""
        prj2 = ""
        if prj.find("CRIME_INDE")>=0:
                crimecount = 1
                print 'using crime index'
        elif prj2.find("UNIVERSITY")>=1:
                unicount = 2
                print 'using university status'
               
        # set field to determine where clause variables 1=crime 2=university 3=crime and university else: none selected
        usecityfield = crimecount + unicount
       
        if usecityfield == 1:
                arcpy.SelectLayerByAttribute_management("citiesL", "SUBSET_SELECTION", crimefieldindex)
                arcpy.CopyFeatures_management("citiesL", "citycrime")
        elif usecityfield == 2:
                arcpy.SelectLayerByAttribute_management("citiesL", "SUBSET_SELECTION", universityfieldindex)
                arcpy.CopyFeatures_management("citiesL", "cityuni")
        elif usecityfield == 3:
                arcpy.SelectLayerByAttribute_management("citiesL", "SUBSET_SELECTION", crimefieldindex + universityfieldindex)
                arcpy.CopyFeatures_management("citiesL", "citycrimeuni")
        else:
                # write selected features to a new featureclass
                arcpy.CopyFeatures_management("citiesL", "SUBSET_SELECTION")

except:
        print arcpy.GetMessages()

Multiple Python scrips on features classes in same file geodatabase

$
0
0
I have about 5 Python scripts running through Windows Task Scheduler (2008 R2) - they run at varying intervals but will occasionally kick off at the same time (for instance if one is on a 10 min internal, the other 30, and the other 60). They operate on separate feature classes in the same file geodatabase, performing a combination of projections and appends. I regularly but not predictably (or reproducibly) get errors relating to an inability to access a certain feature class (even though it exists). Sometimes there is a lock, sometimes the script says it just can't find it (even though it is most certainly there and no other script is operating on the feature class). Anyway, is there any known issues with multiple python scripts running at once on different feature classes in the same geodatabase. I can't for the life of me reproduce or figure out why these errors are occurring (granted they only occur about 7% of the time, but still, on 10 minute intervals this ends of being a lot of errors).

New to python, mapping question

$
0
0
Hello,

I am relatively new to python and I am trying to create a script that will iterate through the features in a feature class, zoom to each one and export the view as a PDF. Assuming I set up all of the labeling and such beforehand can I do this with using a search cursor and the zoomToSelectedFeatures method?

Thomas Kazmierczak

Minimum Attribute and replacing 0 with no data value

$
0
0
Hi,
I've performed some massive OD cost matrices, and then using the pivot table function, I have the results in a table where each row is an origin and each column is a destination and all the values are the travel times between the origins and destinations.

Now I need to do several things:
a) calculate the TIME to the closest facility (ignoring the 0's which are really no data)
b) calculate the NAME of the facility which is the closest
c) replace all the 0 values (an artifact of the pivot table function, which uses a 0 to indicate when no origin-destination solution was found) with our no data value (-1).


My python skills are novice level. I managed to accomplish Task (a) with the following:
def mingt(a, b, c, d, e, f):
L = [a,b,c,d,e,f]
if L != [0,0,0,0,0,0]:
M = min(x for x in L if x!=0)
return M
else:
return -1


For task (b), I want the name of the attribute for which I returned the value in task (a). I'm a bit lost in how to access the name of the attribute. So, any suggestions would be great.

For task (c), I'm guessing this is a massive loop, but I'm hoping some folks have some smart ideas on how to do this as I have a table that is 900,000 rows by 240 columns as well as a bunch of smaller, but still large tables.

Thanks for any help,
Heather

Which side of a line

$
0
0
How can I find which side of a line an object is on? I need to know which side of a line a point falls on.
Viewing all 2485 articles
Browse latest View live