Python:  Using sys.argv[1] in Update Cursor

1060
5
08-09-2010 01:41 PM
JamesHood
Occasional Contributor
Hello,

I would like to create tool for multiple users with multiple datasets from multiple sources. Each dataset contains the same data, it's just stored differently, mostly just different field names and input locations etc...

Is it possible to insert a variable into an Update Cursor to give the tool more flexibility with multiple users?

For example:

InAge = sys.argv[1]

rows = gp.UpdateCursor("c:\temp\test.dbf")
row = rows.Next()
while row:
    if row.InAge == 25:
        row.Range = "Mid"



Will InAge work as a variable? Or will the cursor look for a field called "InAge" ?

Is this even possible ?

Thanks!
0 Kudos
5 Replies
JasonScheirer
Occasional Contributor III
Use the getattr builtin:

InAge = gp.GetParameterAsText(0)

rows = gp.UpdateCursor("c:\temp\test.dbf")
row = rows.Next()
while row:
    if getattr(row, InAge) == 25:
        row.Range = "Mid"
0 Kudos
JamesHood
Occasional Contributor
I ran a test on that and it works like a charm!

I tried to take it a step further though and I found that I can't use the getattr ( , ) function to allow the user to define what the input field name will be. 

InAge = gp.GetParameterAsText(0)
OutField = gp.GetParameterAsText(1)

rows = gp.UpdateCursor("c:\temp\test.dbf")
row = rows.Next()
while row:
    if getattr(row, InAge) == 25:
        getattr(row, OutField) = "Mid" #<-- DOES NOT WORK: RETURNS SYNTAX ERROR AT THIS LINE
        #row.Range = "Mid"


"ERROR: Failed to check - syntax error - can't assign to function call (test.py, line 23)"

I guess the reason it fails is this:  In the if line " if getattr(row, InAge) == 25:"  we are assigning a user value to the variable then asking IF it equals 25, do the following:

Then in the following, we assigning another user value to the variable to be the FieldName,  but then immediately trying to re-assign a new value, changing the FieldName, to the input value for that field.  Then python gets confused and screwy. 

Unless there is some kind of list or tuple or something that would allow the storage of more than one value in the attribute to be used in this circumstance,  I don't know if it would ever work...

Thanks jscheirer,

- James
0 Kudos
JasonScheirer
Occasional Contributor III
Use setattr:

setattr(row, OutField, "Mid")
0 Kudos
ChrisSnyder
Regular Contributor III
Jason:

So is getattr() and setattr() preferable to the esri cursor methods of getvalue() and setvalue(). That is to say, are they faster or for some other reason better? Regardless, seems pretty cool!
0 Kudos
JasonScheirer
Occasional Contributor III
Functionally they are the same, just getattr and setattr will work on any Python object, not just row objects.
0 Kudos