Calculate Field using Fieldnames(variables?!)

المشرف العام

Administrator
طاقم الإدارة
the Question I have is kind of asked before. But I couldn't figure out the solution.

ArcGIS 10.2.2Python 2.7.5

I`m adding fields to a table using user input for the fieldnames. Then I populate those fields and calculate with these fields yet another field.

It looks like this:

fieldname1 = arcpy.GetParameterAsText(2)fieldname2 = arcpy.GetParameterAsText(3)arcpy.AddField_management(FC, fieldname1, "SHORT","", "", "", "", "NULLABLE")arcpy.AddField_management(FC, fieldname2, "SHORT","", "", "", "", "NULLABLE")In the tool the datatype for the user input is set to "String".

Then I use search and update cursor to populate those fields. Afterwards I want to calculate the next field, so I build a codeblock and an expression and use CalculateField_management:

codeblock = """def myFunction(mthree, mtwo): if mthree >= 1 or mtwo >= 3: return -3 elif mthree == 0 and (mtwo==1 or mtwo==2): return -2 elif mthree == 0 and mtwo < 3 and mone >= 5: return -2 if mthree == 0 and mtwo == 0 and mone ==4: return -1"""expression = 'myFunction(fieldname1, fieldname2)'arcpy.CalculateField_management(FC, "EPK_Gesamt",expression,"PYTHON_9.3",codeblock)and that doesn't work. I tried several thing such as:

fieldn1 = '"!{}!"'.format(fieldname1)fieldn2 = '"!{}!"'.format(fieldname2)expression = 'myFunction(fieldn1, fieldn2)'or:

expression = "myFunction('!' + fieldname1 + '!','!' + fieldname2 + '!')'In both cases python returns me text values instead of fieldnames which doesn't work for the calculation in the calculatefield tool.

It works fine if I use the actual fieldnames in the expression variable:

expression = 'myFunction(!example1!, !example2!)'But of course I want to use the user input, so the user doesnt have to work in the script.Anyone knows how to deal with that?



أكثر...
 
أعلى