def add_gdb_field(path, gdb_name, fc, field_dict): arcpy.env.workspace = path + '/' + gdb_name if field_dict['field_domain'] != None: if field_dict['default_value'] != None: arcpy.AddField_management( fc, field_name=field_dict['field_name'], field_type=field_dict['field_type'], field_length=field_dict['field_length'], field_alias=field_dict['field_alias'], field_is_nullable=field_dict['field_is_nullable'], field_domain=field_dict['field_domain']) arcpy.AssignDefaultToField_management( in_table=fc, field_name=field_dict['field_name'], default_value=field_dict['default_value']) else: arcpy.AddField_management( fc, field_name=field_dict['field_name'], field_type=field_dict['field_type'], field_length=field_dict['field_length'], field_alias=field_dict['field_alias'], field_is_nullable=field_dict['field_is_nullable'], field_domain=field_dict['field_domain']) else: if field_dict['field_type'] == "TEXT": arcpy.AddField_management( fc, field_name=field_dict['field_name'], field_type=field_dict['field_type'], field_length=field_dict['field_length'], field_alias=field_dict['field_alias'], field_is_nullable=field_dict['field_is_nullable']) elif field_dict['field_type'] == "LONG": arcpy.AddField_management( fc, field_name=field_dict['field_name'], field_type=field_dict['field_type'], field_precision=field_dict['field_length'], field_alias=field_dict['field_alias'], field_is_nullable=field_dict['field_is_nullable']) else: arcpy.AddField_management( fc, field_name=field_dict['field_name'], field_type=field_dict['field_type'], field_alias=field_dict['field_alias'], field_is_nullable=field_dict['field_is_nullable'])
def add_gdb_field(path, gdb_name, fc_key, fc, field_dict, domains_dict): arcpy.env.workspace = path + '/' + gdb_name if field_dict['field_domain'] != None: if field_dict['field_domain'] == "FIELDKEY": field_domain = fc_key arcpy.AddField_management( fc, field_name=field_dict['field_name'], field_type=field_dict['field_type'], field_length=field_dict['field_length'], field_alias=field_dict['field_alias'], field_is_nullable=field_dict['field_is_nullable'], field_domain=field_domain) else: if field_dict['default_value'] != None: arcpy.AddField_management( fc, field_name=field_dict['field_name'], field_type=field_dict['field_type'], field_length=field_dict['field_length'], field_alias=field_dict['field_alias'], field_is_nullable=field_dict['field_is_nullable'], field_domain=field_dict['field_domain']) arcpy.AssignDefaultToField_management( in_table=fc, field_name=field_dict['field_name'], default_value=field_dict['default_value']) else: arcpy.AddField_management( fc, field_name=field_dict['field_name'], field_type=field_dict['field_type'], field_length=field_dict['field_length'], field_alias=field_dict['field_alias'], field_is_nullable=field_dict['field_is_nullable'], field_domain=field_dict['field_domain']) else: arcpy.AddField_management( fc, field_name=field_dict['field_name'], field_type=field_dict['field_type'], field_length=field_dict['field_length'], field_alias=field_dict['field_alias'], field_is_nullable=field_dict['field_is_nullable']) print("Field {} added to Feature Class {}".format(field_dict['field_name'], fc))
def save_defaultvalue_domain(): #保存 #a = domain_dictionary() all_lst = [] del_domain = [] ds_dic ={} for ds in list_feature_batch('Pipe.gdb'): print ds arcpy.env.workspace = ds fc_dic = {} for fc in arcpy.ListFeatureClasses(): # 为要素类是使用 fld_dic = {} print "正在执行函数" print fc + '\n' for fld in arcpy.ListFields(fc): if fld.domain: #try: if fld.type == 'Integer': # 读取字段类型时,长整型:integer 字符串:String 短整型:SmallInteger domname_defvalue = [] default_val = fld.defaultValue domain_name = fld.domain domname_defvalue.append(default_val) domname_defvalue.append(domain_name) print "\t正在执行函数" print '\t',domain_name,default_val if domain_name not in del_domain: del_domain.append(domain_name) #arcpy.AssignDefaultToField_management(fc,fld.name,"","","True")#有默认值的情况 # 去除域值,去除default value try: arcpy.AssignDefaultToField_management(fc, fld.name, "", "", "true") # 去除default value arcpy.RemoveDomainFromField_management(fc, fld.name) # 去除域值 arcpy.AlterField_management(fc,fld.name,'','','Short') except arcpy.ExecuteError: print arcpy.GetMessages() #fld_dic[fld.name] = domname_defvalue #print domname_defvalue #fldname_domname_defvalue.append(fld_dic) fld_dic[fld.name] = domname_defvalue # print fld_dic fc_dic[fc] = fld_dic ds_dic[os.path.basename(ds)] = fc_dic #print fc_dic all_lst.append(ds_dic) all_lst.append(del_domain) return all_lst
def removeDefaultValues(dataset): # exported source fields may contain DefaultValues, which can replace None/null values in field calculations sourceFields = arcpy.ListFields( dataset) # xmlDoc.getElementsByTagName("SourceField") #stypes = arcpy.da.ListSubtypes(dataset) # my current understanding is that the intermediate/exported dataset will not have subtypes, just default/0 subtype if present in source dataset. dla.addMessage( "Removing Default Value property from intermediate database fields") for sfield in sourceFields: fname = sfield.name if sfield.defaultValue != None: try: arcpy.AssignDefaultToField_management( in_table=dataset, field_name=fname, default_value=None, clear_value=True) # clear the Defaults except: dla.addMessage( "Unable to set DefaultValue for " + fname ) # skip GlobalIDs/other fields that cannot be updated. Should not have a default set in these cases
def crearFeature(ubigeo, dataset): nombreFc = 'SCR_{}'.format(ubigeo) Campos_SCR = [("UBIGEO", "TEXT", "6"), ("SCR", "SHORT", "5")] fc_tmp = arcpy.CreateFeatureclass_management("in_memory", '{}_TMP'.format(nombreFc), "POLYGON", "#", "#", "#", arcpy.SpatialReference(4326)) for n in Campos_SCR: if n[1] == "TEXT": arcpy.AddField_management(fc_tmp, n[0], n[1], '#', '#', n[2], '#', 'NULLABLE', 'NON_REQUIRED', '#') else: arcpy.AddField_management(fc_tmp, n[0], n[1], n[2], '#', '#', '#', 'NULLABLE', 'NON_REQUIRED', '#') scr = arcpy.CreateFeatureclass_management(dataset, nombreFc, "POLYGON", fc_tmp, "#", "#", arcpy.SpatialReference(4326)) arcpy.AssignDefaultToField_management(scr, 'UBIGEO', ubigeo) return scr
def recover_fld_domain(): arcpy.env.workspace = r"D:\全生命周期" for ds in list_feature_batch('Pipe.gdb'): #print ds blst = save_defaultvalue_domain() for ds_item, fc_dic_item in blst[0].items(): if ds_item == os.path.basename(ds): print ds arcpy.env.workspace = ds for fc_item,fld_dic in fc_dic_item.items(): print "正在执行主程序" for fc in arcpy.ListFeatureClasses(): # 为要素类是使用 if fc == fc_item: print fc + '\n' for fld in arcpy.ListFields(fc): for fld_item,domain_dflt_lst in fld_dic.items(): if fld_item == fld.name: #fld.domain = domain_dflt_lst[1] try: arcpy.AssignDomainToField_management(fc,fld.name,domain_dflt_lst[1]) except arcpy.ExecuteError: print arcpy.GetMessages() print 10 * '#' print "图层:" + fc + ' ' + '字段:' + fld.name + ' ' + "名称为" + domain_dflt_lst[1] +'的阈值不存在' #fld.defaultValue = domain_dflt_lst[0] if domain_dflt_lst[0] is not None: try: arcpy.AssignDefaultToField_management(fc,fld.name,int(domain_dflt_lst[0]),"","false") except arcpy.ExecuteError: print arcpy.GetMessages() print 10*"%" print fc,fld.name,domain_dflt_lst[0] print 10 * "%"
def xu_ly_duong_mep_nuoc(self): arcpy.env.overwriteOutput = 1 inFeatures = [[self.duong_dan_nguon + "ThuyHe/" + self.lop_thuy_he, 1], [self.duong_dan_nguon + "ThuyHe/" + self.lop_bai_boi, 2]] intersectOutput = self.duong_dan_nguon + "ThuyHe/" + self.lop_duong_mep_nuoc + "_" + self.lop_thuy_he arcpy.Intersect_analysis(inFeatures, intersectOutput, "NO_FID", None, "LINE") arcpy.DeleteField_management(intersectOutput, [ "loaiTrangThaiNuocMat", "ten", "doRong", "maNhanDang_1", "ngayThuNhan_1", "ngayCapNhat_1", "maDoiTuong_1", "ten_1", "loaiBaiBoi", "loaiTrangThaiXuatLo", "nguonDuLieu_1", "maTrinhBay_1", "tenManh_1", "soPhienHieuManhBanDo_1" ]) arcpy.AddField_management(intersectOutput, "loaiRanhGioiNuocMat", "LONG", None, None, None, "Loai ranh gioi nuoc mat", "NULLABLE", None, "LoaiRanhGioiNuocMat") arcpy.CalculateField_management(intersectOutput, "loaiRanhGioiNuocMat", self.loai_ranh_gioi_nuoc_mat, "PYTHON_9.3") arcpy.AssignDefaultToField_management(intersectOutput, "maDoiTuong", "LG02", None) arcpy.CalculateField_management(intersectOutput, "maDoiTuong", "'LG02'", "PYTHON_9.3")
#Name: setSubTypeDefaultValues.py #Purpose: set default values for a domain associated # with a subtype import arcpy fc = ( r"\\ad.utah.edu\sys\FM\gis\ags_10_3\ags_content\sde_connection_files\sdeadmin@FM-GISSQLHA_DEFAULT_VERSION.sde\uusd.DBO.Grounds\UUSD.DBO.Tree" ) subtypes = arcpy.da.ListSubtypes(fc) subtypeCodes = [] for stcode, stdict in subtypes.iteritems(): subtypeCodes.append(stcode) ##for fields in arcpy.ListFields(fc): ## print fields.name print subtypeCodes for code in subtypeCodes: arcpy.AssignDefaultToField_management(fc, "tree_lifecycle", "Active", code) print str(code) + "tree_lifecycle complete" arcpy.AssignDefaultToField_management(fc, "plaque", 0, code) print str(code) + "plaque complete\n" print "script done"
del uc # prep unitTable if not arcpy.Exists(unitTable): print('%s not found') % unitTable quit() #arcpy.ImportXMLWorkspaceDocument_management(workspace, MM_POLEEQUIPMENT_XML, "Schema_Only") #print('Setting default value: %s) % (stormName) #arcpy.AssignDefaultToField_management(unitTable,"StormName",stormName) #print('Setting default value: %i) % (sapNetwork) #arcpy.AssignDefaultToField_management(unitTable,"SAPNetwork",sapNetwork) else: print 'Truncating...', unitTable arcpy.TruncateTable_management(unitTable) arcpy.AssignDefaultToField_management(unitTable, "StormName", stormName) #print 'Checking for index eSupportStructure_GLOABLID...' #indexes = arcpy.ListIndexes(unitTable) #indexNames = [] #for index in indexes: # print index.name # indexNames.append(index.name) #if "IDX_poleGUID" not in indexNames: # print'You need to add the Index' #arcpy.AddIndex_management (truncTable, "eSupportStructure_GLOBALID", "IDX_poleGUID", "UNIQUE", "ASCENDING") # Start Main with arcpy.da.Editor(workspace) as edit: print 'Inserting...', poleFC ic = arcpy.da.InsertCursor(unitTable, PoleFldsDest) with arcpy.da.SearchCursor(connectionRoot % (poleFC), PoleFldsOrig) as sc: for scrow in sc:
else: arcpy.CreateFeatureclass_management(gdb_location+"\\"+gdb_name+".gdb", fc_name, fc_type, "", has_m, has_z, spat_ref) arcpy.AddMessage ("Sasquatch created"+in_Table) arcpy.SetParameterAsText(11, gdb_location+"\\"+gdb_name) #Create required PUBLICDISPLAY Field try: in_Field = "PUBLICDISPLAY" default = "No Public Map Display" #Check if field exists in the FC if len(arcpy.ListFields(in_Table,in_Field))>0: arcpy.AddWarning (in_Field+" exits already") #If not, create it else: arcpy.AddField_management(gdb_location+"\\"+gdb_name+".gdb\\"+fc_name, in_Field, "TEXT", "", "", 50, in_Field, "NON_NULLABLE", "REQUIRED", "DOM_PUBLICDISPLAY_NPS2016") arcpy.AddMessage ("Sasquatch created the "+in_Field+" field and the attribute domain is DOM_PUBLICDISPLAY_NPS2016") arcpy.AssignDefaultToField_management(gdb_location+"\\"+gdb_name+".gdb\\"+fc_name, in_Field, default) arcpy.AddMessage ("Saquatch assigned "+default+" as the default value for "+ in_Field) except arcpy.ExecuteError: msgs = arcpy.GetMessages(2) arcpy.AddError(msgs) except: tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1]) msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n" arcpy.AddError(pymsg) arcpy.AddError(msgs) #Create required DATAACCESS Field try:
def add_field(): for _fc in fcDict: if _fc in fc2attr_dict: _fc_attr_list = fc2attr_dict[_fc] _in_table = "" if fcDict[_fc] == "TABLE": _in_table = os.path.join(get_workspace(), _fc) else: _in_table = os.path.join(get_workspace(), featuredataset, _fc) if arcpy.Exists(_in_table): for _attr in _fc_attr_list: _field_name = _attr[0] if field_exists(_in_table, _field_name) is False: _field_type = attrTypeDict[_attr[1]][0] _field_precision = 0 _field_scale = 0 _field_length = 0 _field_alias = "#" _field_is_nullable = True _field_is_required = False _field_domain = "#" if _field_type == "DOUBLE": _field_precision = attrTypeDict[_attr[1]][1] _field_scale = attrTypeDict[_attr[1]][2] elif _field_type == "SHORT": pass elif _field_type == "SHORT_DOMAIN": _field_type = "SHORT" _field_domain = attrTypeDict[_attr[1]][1] elif _field_type == "LONG": pass elif _field_type == "LONG_DOMAIN": _field_type = "LONG" _field_domain = attrTypeDict[_attr[1]][1] elif _field_type.startswith("TEXT") is True: _field_length = attrTypeDict[_attr[1]][1] elif _field_type == "DATE": pass elif _field_type == "GUID": pass arcpy.AddField_management( in_table=_in_table, field_name=_field_name, field_type=_field_type, field_precision=_field_precision, field_scale=_field_scale, field_length=_field_length, field_alias=_field_alias, field_is_nullable=_field_is_nullable, field_is_required=_field_is_required, field_domain=_field_domain, ) print("Field created:" + _fc + "." + _field_name) else: print("Field already created: " + _fc + "." + _field_name) if len(_attr) > 2: print(" Set default value: " + str(_attr[2])) arcpy.AssignDefaultToField_management( in_table=_in_table, field_name=_field_name, default_value=_attr[2], ) else: print(_in_table + " not found")
def create_structures_fc(gdb): """ Create Historic Structures feature class """ arcpy.env.workspace = gdb fc = "HistoricStructures" spatref = arcpy.SpatialReference( "WGS 1984 Web Mercator (auxiliary sphere)") if arcpy.Exists(fc): arcpy.Delete_management(os.path.join(gdb, fc)) has_m = "DISABLED" has_z = "DISABLED" # Execute CreateFeatureclass arcpy.CreateFeatureclass_management(gdb, fc, "POINT", "", has_m, has_z, spatref) arcpy.AddField_management(fc, "ResourceID", "LONG", "", "", "", "Resource ID", "NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(fc, "PropName", "TEXT", "", "", 100, "Resource Name", "NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(fc, "StrucType", "LONG", "", "", "", "Structure Type", "NON_NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(fc, "BldType", "TEXT", "", "", 3, "Building Type", "NON_NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(fc, "StyleType", "TEXT", "", "", 3, "Architectural Style", "NON_NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(fc, "Eligibility", "TEXT", "", "", 3, "Eligibility Status", "NON_NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(fc, "ConstYr", "LONG", "", "", "", "Construction Year", "NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(fc, "Address", "TEXT", "", "", 200, "Address", "NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(fc, "Notes", "TEXT", "", "", 200, "Notes", "NULLABLE", "NON_REQUIRED", "") arcpy.AddGlobalIDs_management(fc) arcpy.AddField_management(fc, "EPProject", "TEXT", "", "", 20, "EPEI Project ID", "NULLABLE", "NON_REQUIRED", "") arcpy.SetSubtypeField_management(fc, "StrucType") for item in subtypes.items(): arcpy.AddSubtype_management(fc, item[0], item[1]) arcpy.SetDefaultSubtype_management(fc, 5) for item in subtypes.items(): arcpy.AssignDomainToField_management(fc, "BldType", item[1], item[0]) arcpy.AssignDomainToField_management( fc, "StyleType", "Styles", ['0', '1', '2', '3', '4', '5', '6', '7', '8']) arcpy.AssignDomainToField_management( fc, "Eligibility", "Eligibility", ['0', '1', '2', '3', '4', '5', '6', '7', '8']) arcpy.AssignDefaultToField_management( fc, "Eligibility", "U", ['0', '1', '2', '3', '4', '5', '6', '7', '8']) arcpy.AssignDefaultToField_management( fc, "StyleType", "NS", ['0', '1', '2', '3', '4', '5', '6', '7', '8']) arcpy.AssignDefaultToField_management( fc, "BldType", "OT", ['0', '1', '2', '3', '4', '6', '7', '8']) arcpy.AssignDefaultToField_management(fc, "BldType", "NAT", '5') return os.path.join(gdb, fc)
def AddCodedTextDomain(feature_list, workspace, domain_name, code_list, assign_default=False, populate_default=False): """ Applies the code_list as a domain to the list of feature classes. Domain must be the same as the field name to which it is being applied. :param feature_list: list of feature classes :param workspace: the project's unique gdb :param domain_name: name of the domain as a string, must be same as name of field to which it is applied :param code_list: list of codes as strings :param assign_default: True to assign the first code in the code_list as default :param populate_default: True to populate existing features with the default code :return: None """ # Create unique list from provided uniqueCodes = [] for code in code_list: if code not in uniqueCodes: uniqueCodes.append(code) # Check for existence of domain; update domain if present, add domain if not desc = arcpy.Describe(workspace) domains = desc.domains if domain_name in domains: arcpy.AddMessage(domain_name + " is already specified as a domain") try: # try removing from all fields in all feature classes existingFeatures = arcpy.ListFeatureClasses() for existingFeature in existingFeatures: fields = arcpy.ListFields(existingFeature) for field in fields: if field.domain == domain_name: arcpy.RemoveDomainFromField_management( existingFeature, field.name) arcpy.AddMessage(domain_name + " domain removed from " + existingFeature + " " + field.name + " field") # try removing from all fields in all subtypes # Credit to:(https://community.esri.com/thread/ # 198384-how-to-remove-domain-from-field-for-gdb) subtypes = arcpy.da.ListSubtypes(existingFeature) for stcode, stdict in list(subtypes.items()): for stkey in list(stdict.keys()): # if there is a Subtype Field if not stdict['SubtypeField'] == '': st_code = "'{}: {}'".format(stcode, stdict['Name']) # if no Subtype Field, use "#" in RemoveDomainFromField # for subtype_code else: st_code = "#" if stkey == 'FieldValues': fields = stdict[stkey] for field, fieldvals in list(fields.items()): # if field has a domain if not fieldvals[1] is None: # and the domain is in our list if fieldvals[1].name == domain_name: # remove the domain arcpy.AddMessage(fieldvals[1].name + " domain removed " + "from " + existingFeature + " field: " + field + " subtype: " + st_code) arcpy.RemoveDomainFromField_management( existingFeature, field, st_code) arcpy.DeleteDomain_management(workspace, domain_name) arcpy.CreateDomain_management(workspace, domain_name, "Valid " + domain_name + "s", "TEXT", "CODED") for code in uniqueCodes: arcpy.AddCodedValueToDomain_management(workspace, domain_name, code, code) for feature in feature_list: try: arcpy.AssignDomainToField_management( feature, domain_name, domain_name) # Check to make sure subtypes exist subtypes = arcpy.da.ListSubtypes(feature) if len(subtypes ) == 1 and subtypes[0]['SubtypeField'] == '': pass else: st_codes = [ str(stcode) for stcode, stdict in list(subtypes.items()) ] arcpy.AssignDomainToField_management( feature, domain_name, domain_name, st_codes) except arcpy.ExecuteError: arcpy.AddMessage("--------------------------------" "\n" + domain_name + " domain for feature \n\n" + str(feature) + "\n\n" + "could not be updated. Use " "caution when populating attribute\n" "---------------------------------") arcpy.AddMessage(domain_name + " domain updated") except arcpy.ExecuteError: arcpy.AddMessage(domain_name + " domain could not be updated. Use " "caution when populating attribute") else: arcpy.CreateDomain_management(workspace, domain_name, "Valid " + domain_name + "s", "TEXT", "CODED") for code in uniqueCodes: arcpy.AddCodedValueToDomain_management(workspace, domain_name, code, code) for feature in feature_list: try: arcpy.AssignDomainToField_management(feature, domain_name, domain_name) # Check to make sure subtypes exist subtypes = arcpy.da.ListSubtypes(feature) if len(subtypes) == 1 and subtypes[0]['SubtypeField'] == '': pass else: st_codes = [ str(stcode) for stcode, stdict in list(subtypes.items()) ] arcpy.AssignDomainToField_management( feature, domain_name, domain_name, st_codes) except arcpy.ExecuteError: arcpy.AddMessage(domain_name + " domain could not be updated. Use " "caution when populating attribute") arcpy.AddMessage(domain_name + " domain updated") # Assign the first value as the default if assign_default: for feature in feature_list: subtypes = arcpy.da.ListSubtypes(feature) if len(subtypes) == 1 and subtypes[0]['SubtypeField'] == '': arcpy.AssignDefaultToField_management(feature, domain_name, uniqueCodes[0]) else: st_codes = [ str(stcode) for stcode, stdict in list(subtypes.items()) ] arcpy.AssignDefaultToField_management(feature, domain_name, uniqueCodes[0], st_codes) # Populate field with default values if Null if populate_default: arcpy.AddMessage("Populating default values") for feature in feature_list: where_clause = "{0} = '' OR {0} IS NULL".format( arcpy.AddFieldDelimiters(feature, domain_name)) with arcpy.da.UpdateCursor(feature, domain_name, where_clause) as cursor: for row in cursor: row[0] = uniqueCodes[0] cursor.updateRow(row)
arcpy.AddError(msgs) #Grab the Feature Class #fc_name = gdb_name+"\\"+fc_name #Create required PUBLICDISPLAY Field try: in_Field = "PUBLICDISPLAY" default = "No Public Map Display" if len(arcpy.ListFields(fc_name,in_Field))>0: arcpy.AddWarning (in_Field+" exits already") else: arcpy.AddWarning (in_Field+" doesn't exist") arcpy.AddField_management(fc_name, in_Field, "TEXT", "", "", 50, in_Field, "NON_NULLABLE", "REQUIRED", "DOM_PUBLICDISPLAY_NPS2016") arcpy.AddMessage ("Sasquatch created the "+in_Field+" field and the attribute domain is DOM_PUBLICDISPLAY_NPS2016") arcpy.AssignDefaultToField_management(fc_name, in_Field, default) arcpy.AddMessage ("Saquatch assigned "+default+" as the default value for "+ in_Field) except arcpy.ExecuteError: msgs = arcpy.GetMessages(2) arcpy.AddError(msgs) except: tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1]) msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n" arcpy.AddError(pymsg) arcpy.AddError(msgs) #Create required DATAACCESS Field try:
arcpy.env.workspace = r'D:\Grad_Spring2019\610-Programming\Exercise3\Exercise 3.gdb' #create feature class path = r'D:\Grad_Spring2019\610-Programming\Exercise3\Exercise 3.gdb' featureClass = arcpy.CreateFeatureclass_management(path, 'Question8') #add a field fieldName = 'Places' arcpy.AddField_management(featureClass, fieldName, 'TEXT') #add a domain gdb = r'D:\Grad_Spring2019\610-Programming\Exercise3\Exercise 3.gdb' fc = 'Question8' domain = 'Places' field = 'Places' arcpy.CreateDomain_management(gdb, domain, 'places', 'TEXT', 'CODED') domDict = { 'WLDNS': 'Wilderness', 'LK': 'Lake', 'RV': 'River', 'CG': 'Camp Ground', 'OT': 'Other' } for code in domDict: arcpy.AddCodedValueToDomain_management(gdb, domain, code, domDict[code]) arcpy.AssignDefaultToField_management(fc, field, domain)
def createUN(jsonFile, outGDB): cfgStr = open(jsonFile, 'r', encoding='gbk').read() unObj = json.loads(cfgStr) unName = unObj["unName"] # 创建un和结构网络 arcpy.env.preserveGlobalIds = True arcpy.env.overwriteOutput = True arcpy.CreateFileGDB_management(os.path.dirname(outGDB), os.path.basename(outGDB)) arcpy.pt.StageUtilityNetwork(outGDB, unObj["territoryFeaCls"], unObj["feaDS"], unName) # Tips:尽量使用相对路径,如有工具不支持再改用绝对路径 arcpy.env.workspace = os.path.join(outGDB, unObj["feaDS"]) # 导入fieldDomains,domain是面向GDB级的物理设置 for domain in unObj["fieldDomains"]: dName = domain["name"] if domain.get("dtype") == "RANGE": arcpy.CreateDomain_management(outGDB, dName, domain.get("desc", dName), domain.get("ftype", "SHORT"), "RANGE") arcpy.SetValueForRangeDomain_management(outGDB, dName, domain['min'], domain['max']) continue table = arcpy.management.CreateTable('in_memory', dName)[0] # ?[0] arcpy.AddField_management(table, 'code', domain.get("ftype", "SHORT")) arcpy.AddField_management(table, 'name', 'TEXT', field_length=254) with arcpy.da.InsertCursor(table, ('code', 'name')) as cur: for v in domain["values"]: cur.insertRow((v["code"], v["name"])) arcpy.TableToDomain_management(table, 'code', 'name', outGDB, dName, domain.get("desc", dName), update_option='REPLACE') arcpy.Delete_management(table) # 创建除了structure以外的域网络 for dnObj in unObj["domainNetworks"]: if dnObj["name"].lower() != "structure": arcpy.AddDomainNetwork_un(unName, dnObj["name"], dnObj["tierDef"], dnObj["controllerType"], dnObj.get("alias")) # 添加TerminalConfiguration,categories,netAttributes,这些是面向整个UN级的逻辑设置 # Tips:需要先创建至少一个域网络,才能添加TerminalConfiguration terminalConfigs = unObj.get("terminalConfigs") if terminalConfigs: for terminalCfg in terminalConfigs: if terminalCfg["dir"] == "DIRECTIONAL": arcpy.AddTerminalConfiguration_un( unName, terminalCfg["name"], "DIRECTIONAL", terminals_directional=terminalCfg["terminals"], valid_paths=terminalCfg["paths"], default_path=terminalCfg.get("default")) else: arcpy.AddTerminalConfiguration_un( unName, terminalCfg["name"], "BIDIRECTIONAL", terminals_bidirectional=terminalCfg["terminals"], valid_paths=terminalCfg["paths"], default_path=terminalCfg.get("default")) # TODO: 网络分组与分层的区别? categories = unObj.get("categories") if categories: ## 为什么加这种判断 for category in categories: arcpy.AddNetworkCategory_un(unName, category) # TODO:网络属性的可选设置有什么作用? netAttributes = unObj.get("netAttributes") if netAttributes: for attrib in netAttributes: arcpy.AddNetworkAttribute_un(unName, attrib["name"], attrib["type"], attrib.get("inline"), attrib.get("apportionable"), attrib.get("domain"), attrib.get("overridable"), attrib.get("nullable"), attrib.get("substitution"), attrib.get("attrToSubstitution")) # 添加子类,创建新字段,指定属性域,指定网络属性,这些是面向Table级的物理设置 for dnObj in unObj["domainNetworks"]: # 子类已经自动设置为ASSETGROUP字段,添加自定义值 subtypes = dnObj.get("subtypes") if subtypes: for subtype in subtypes: for v in subtype["values"]: arcpy.AddSubtype_management(subtype["feaCls"], v["code"], v["name"]) if subtype.get("default"): arcpy.SetDefaultSubtype_management(subtype["feaCls"], subtype.get("default")) # 添加自定义字段 newFields = dnObj.get("newFields") if newFields: for field in newFields: length = field.get( "length") if field["type"].upper() == "TEXT" else None arcpy.AddField_management(field["feaCls"], field["name"], field["type"], field_length=length, field_alias=field.get("alias")) # 为字段指定属性域 fDomains = dnObj.get("fieldDomains") if fDomains: for fd in fDomains: arcpy.AssignDomainToField_management(fd["feaCls"], fd["fieldName"], fd["domainName"], fd.get("subtypeCodes")) if fd.get("default"): arcpy.AssignDefaultToField_management( fd["feaCls"], fd["fieldName"], fd["default"], fd.get("subtypeCodes")) # 为字段指定网络属性 netAttributes = dnObj.get("netAttributes") if netAttributes: for attribute in netAttributes: for field in attribute["fields"]: fc, fName = field.split("/") fObj = arcpy.ListFields(fc, fName) if fObj: arcpy.SetNetworkAttribute_un(unName, attribute["name"], dnObj["name"], fc, fName) # 为资产指定多项配置:端子配置、分组、边连通性、角色,这些是面向资产级的逻辑设置 with open(unObj.get("assetsCSV", "not exist"), 'r', encoding='gbk') as fp: reader = csv.reader(fp) # 读取列为列表 header = next( reader ) # ['domainNet', 'feaCls', 'assetName', 'categories', 'terminalCfg', 'edgeConnectivity', 'roleType', 'deletionType', 'viewScale', 'splitType'] assetCfg = namedtuple('assetCfg', header) for row in reader: row = assetCfg(*row) asset = row.assetName.split('/') if row.terminalCfg: arcpy.SetTerminalConfiguration_un(unName, row.domainNet, row.feaCls, *asset, row.terminalCfg) if row.categories: arcpy.SetNetworkCategory_un(unName, row.domainNet, row.feaCls, *asset, row.categories) if row.edgeConnectivity: # 边联通非空 arcpy.SetEdgeConnectivity_un(unName, row.domainNet, row.feaCls, *asset, row.edgeConnectivity) if row.roleType: arcpy.SetAssociationRole_un(unName, row.domainNet, row.feaCls, *asset, row.roleType, row.deletionType, row.viewScale, row.splitType) # 创建tier,并设置子网定义,这些是面向子网级的逻辑设置 # TODO: subnetwork_field_name有什么作用?subnetDef还有很多可选设置 for dnObj in unObj["domainNetworks"]: dnName = dnObj["name"] if dnName.lower() != "structure": # tierGroups tierGroups = dnObj.get("tierGroups") if tierGroups and dnObj["tierDef"] == "HIERARCHICAL": for groupName in tierGroups: arcpy.AddTierGroup_un(unName, dnName, groupName) tiers = dnObj.get("tiers") if tiers: for tier in tiers: if dnObj["tierDef"] == "HIERARCHICAL": arcpy.AddTier_un( unName, dnName, tier["name"], tier["rank"], topology_type="MESH", tier_group_name=tier.get("groupName"), subnetwork_field_name=tier["subnetField"]) else: arcpy.AddTier_un(unName, dnName, tier["name"], tier["rank"], topology_type=tier["topo"]) arcpy.SetSubnetworkDefinition_un( unName, dnName, tier["name"], tier["disjoint"], tier["devices"], tier["controllers"], tier.get("lines"), tier.get("aggregated"), tier.get("diagrams"), include_barriers=tier.get("barriers"), traversability_scope=tier.get("traverse")) # TODO: 导入rule arcpy.ImportRules_un(unName, "All", "E:/ArcGIS/unnet/rules.csv") # TODO: 导入数据 # 数据导入是基于子类的,把要素类路径写入到子类中,修改了demoUN域网络的子类型值 for dnObj in unObj["domainNetworks"]: subtypes = dnObj.get("subtypes") if subtypes: for subtype in subtypes: for v in subtype["values"]: arcpy.Append_management(subtype["path"], subtype["feaCls"], "NO_TEST", subtype=v["name"])
def main(): # GET PARAMETER VALUES New_Anthro_Features = arcpy.GetParameterAsText(0) Existing_Anthro_Features = arcpy.GetParameterAsText(1) replace_subtypes = arcpy.GetParameterAsText(2) # Overwrite outputs arcpy.env.overwriteOutput = True # Helper functions (from ccslib) def Str2Bool(string): """ Converts a string to Python boolean. If not 'true' in lowercase, returns False. :param string: a string of True or False, not cap sensitive :return: Boolean """ if string == 'True' or string == 'true': return True else: return False def AddFields(input_feature, field_to_add, field_types, copy_existing=False): """ Adds provided fields to the input_feature, removes or copies existing of the same name. :param input_feature: a feature class :param field_to_add: a list of field names as strings :param field_types: a list of field types as strings, in order of fields_ to_add :param copy_existing: True to create a copy of any existing field with same name as field to add :return: None """ # Create dictionary of field types mapped to fields to add fieldTypesDict = dict(zip(field_to_add, field_types)) # Copy fields if they exist and delete original existingFields = arcpy.ListFields(input_feature) fieldNames = [each.name.lower() for each in existingFields] for field in field_to_add: if field.lower() in fieldNames: arcpy.AddMessage(field + " field exists.") if copy_existing: arcpy.AddMessage("Copying to new field named " + field + "_copy.") fieldIndex = fieldNames.index(field.lower()) if field.lower() + "_copy" in fieldNames: arcpy.AddMessage("Deleting field " + field + "_copy") arcpy.DeleteField_management(input_feature, field + "_copy") arcpy.AddField_management(input_feature, field + "_copy", existingFields[fieldIndex].type) with arcpy.da.UpdateCursor( input_feature, [field, field + "_copy"]) as cursor: try: for row in cursor: row[1] = row[0] cursor.updateRow(row) except arcpy.ExecuteError: arcpy.AddMessage("Unable to copy from " + field + " to " + field + "_copy.") arcpy.AddMessage("Deleting original field.") arcpy.DeleteField_management(input_feature, field) # Add fields for field in field_to_add: # arcpy.AddMessage("Adding " + field + " field") arcpy.AddField_management(input_feature, field, fieldTypesDict[field], field_length=50) # Main script # Get path to existing anthro features desc = arcpy.Describe(Existing_Anthro_Features) anthro_feature_path = desc.catalogPath # List subtypes from the existing anthro features subtypes = arcpy.da.ListSubtypes(Existing_Anthro_Features) # Add new field "Feature" AddFields(New_Anthro_Features, ['Feature'], ['SHORT']) # Copy new features over existing feature = arcpy.CopyFeatures_management(New_Anthro_Features, anthro_feature_path) replace_subtypes = Str2Bool(replace_subtypes) if replace_subtypes: # Set Feature field to Subtype field arcpy.SetSubtypeField_management(feature, "Feature") # Create subtypes for stcode, stdict in list(subtypes.items()): arcpy.AddSubtype_management(feature, stcode, stdict['Name']) # Iterate through subtypes and update feature code def get_feature_code(subtype_name): for stcode, stdict in list(subtypes.items()): if stdict['Name'] == subtype_name: return stcode with arcpy.da.UpdateCursor(feature, ["Feature", "Subtype"]) as cursor: for row in cursor: row[0] = get_feature_code(row[1]) cursor.updateRow(row) # Apply domains feature_basename = desc.baseName domain_name = feature_basename + "_Subtypes" arcpy.AssignDomainToField_management(feature, "Subtype", domain_name) if len(subtypes) == 1 and subtypes[0]['SubtypeField'] == '': pass else: st_codes = [ str(stcode) for stcode, stdict in list(subtypes.items()) ] arcpy.AssignDomainToField_management(feature, "Subtype", domain_name, st_codes) # Apply defaults for st_code, st_dict in list(subtypes.items()): default = subtypes[st_code]['Name'] arcpy.AssignDefaultToField_management(feature, "Subtype", default, st_code) default_type = feature_basename st_codes = [str(stcode) for stcode, stdict in list(subtypes.items())] arcpy.AssignDefaultToField_management(feature, "Type", default_type, st_codes)
def create_field_types(fgdb_path): """ :param fgdb_path: file path to the file geodatabase :type fgdb_path: basestring """ arcpy.env.workspace = fgdb_path arcpy.env.overwriteOutput = True fc_name = "GDA94_all_field_types_polyline" wkid = 4283 # GDA94 lat/long geometry_type = "POLYLINE" has_m = "DISABLED" has_z = "DISABLED" sr = arcpy.SpatialReference(wkid) arcpy.CreateFeatureclass_management(out_path=fgdb_path, out_name=fc_name, geometry_type=geometry_type, has_m=has_m, has_z=has_z, spatial_reference=sr) Field = collections.namedtuple('Field', [ 'field_name', 'field_type', 'field_precision', 'field_scale', 'field_length', 'field_alias', 'field_is_nullable', 'field_is_required', 'field_domain' ]) text_field = Field(field_name="text_field", field_type="TEXT", field_precision="", field_scale="", field_length="", field_alias="", field_is_nullable="NULLABLE", field_is_required="NON_REQUIRED", field_domain="") float_field = Field(field_name="float_field", field_type="FLOAT", field_precision="", field_scale="", field_length="", field_alias="", field_is_nullable="NULLABLE", field_is_required="NON_REQUIRED", field_domain="") double_field = Field(field_name="double_field", field_type="DOUBLE", field_precision="", field_scale="", field_length="", field_alias="", field_is_nullable="NULLABLE", field_is_required="NON_REQUIRED", field_domain="") short_field = Field(field_name="short_field", field_type="SHORT", field_precision="", field_scale="", field_length="", field_alias="", field_is_nullable="NULLABLE", field_is_required="NON_REQUIRED", field_domain="") long_field = Field(field_name="long_field", field_type="LONG", field_precision="", field_scale="", field_length="", field_alias="", field_is_nullable="NULLABLE", field_is_required="NON_REQUIRED", field_domain="") date_field = Field(field_name="date_field", field_type="DATE", field_precision="", field_scale="", field_length="", field_alias="", field_is_nullable="NULLABLE", field_is_required="NON_REQUIRED", field_domain="") blob_field = Field(field_name="blob_field", field_type="BLOB", field_precision="", field_scale="", field_length="", field_alias="", field_is_nullable="", field_is_required="NON_REQUIRED", field_domain="") raster_field = Field(field_name="raster_field", field_type="RASTER", field_precision="", field_scale="", field_length="", field_alias="", field_is_nullable="NULLABLE", field_is_required="NON_REQUIRED", field_domain="") guid_field = Field(field_name="guid_field", field_type="GUID", field_precision="", field_scale="", field_length="", field_alias="", field_is_nullable="NULLABLE", field_is_required="NON_REQUIRED", field_domain="") text_field_non_nullable = Field(field_name="text_field_non_nullable", field_type="TEXT", field_precision="", field_scale="", field_length="", field_alias="", field_is_nullable="NON_NULLABLE", field_is_required="NON_REQUIRED", field_domain="") short_field_required = Field(field_name="short_field_required", field_type="SHORT", field_precision="", field_scale="", field_length="", field_alias="", field_is_nullable="NULLABLE", field_is_required="REQUIRED", field_domain="") guid_field_alias = Field(field_name="guid_field_alias", field_type="GUID", field_precision="", field_scale="", field_length="", field_alias="Globally Unique ID", field_is_nullable="NULLABLE", field_is_required="NON_REQUIRED", field_domain="") date_field_non_nullable_required_alias = Field( field_name="date_field_non_nullable_required", field_type="DATE", field_precision="", field_scale="", field_length="", field_alias="Required non-null date", field_is_nullable="NULLABLE", field_is_required="REQUIRED", field_domain="") float_field_default_value = Field(field_name="float_field_default_value", field_type="FLOAT", field_precision="", field_scale="", field_length="", field_alias="", field_is_nullable="NULLABLE", field_is_required="NON_REQUIRED", field_domain="") double_field_default_value = Field(field_name="double_field_default_value", field_type="DOUBLE", field_precision="", field_scale="", field_length="", field_alias="", field_is_nullable="NULLABLE", field_is_required="NON_REQUIRED", field_domain="") text_field_default_value = Field(field_name="text_field_default_value", field_type="TEXT", field_precision="", field_scale="", field_length="26", field_alias="", field_is_nullable="NULLABLE", field_is_required="NON_REQUIRED", field_domain="") short_field_default_value = Field(field_name="short_field_default_value", field_type="SHORT", field_precision="", field_scale="", field_length="", field_alias="", field_is_nullable="NULLABLE", field_is_required="NON_REQUIRED", field_domain="") date_field_default_value = Field(field_name="date_field_default_value", field_type="DATE", field_precision="", field_scale="", field_length="", field_alias="", field_is_nullable="NULLABLE", field_is_required="NON_REQUIRED", field_domain="") fields_list = [ text_field, float_field, double_field, short_field, long_field, date_field, blob_field, raster_field, guid_field, text_field_non_nullable, short_field_required, guid_field_alias, date_field_non_nullable_required_alias, float_field_default_value, double_field_default_value, text_field_default_value, short_field_default_value, date_field_default_value ] log.info(str(len(fields_list)) + " fields defined") for field in fields_list: log.info("adding field " + field.field_name) arcpy.AddField_management(fc_name, field.field_name, field.field_type, field.field_precision, field.field_scale, field.field_length, field.field_alias, field.field_is_nullable, field.field_is_required, field.field_domain) arcpy.AssignDefaultToField_management( in_table=fc_name, field_name="float_field_default_value", default_value=123.456) arcpy.AssignDefaultToField_management( in_table=fc_name, field_name="double_field_default_value", default_value=1234567890.012345) arcpy.AssignDefaultToField_management( in_table=fc_name, field_name="text_field_default_value", default_value="abcdefghijklmnopqrstuvwxyz") arcpy.AssignDefaultToField_management( in_table=fc_name, field_name="short_field_default_value", default_value=5) arcpy.AssignDefaultToField_management( in_table=fc_name, field_name="date_field_default_value", default_value="10-08-2018 10:06:55 PM")
def addFieldsFromSchema(schemasFolder, featureClass, schema): # Adds the fields defined in a field schema CSV file to the specified feature class try: arcpy.AddMessage("Starting: AddFieldsFromSchema") # Make sure the feature class exists if arcpy.Exists(featureClass): subTypes = {} # Make sure the specfied field schema CSV file exists fieldSchemaFile = os.path.join(schemasFolder, "Fields_" + schema + ".csv") if os.path.exists(fieldSchemaFile): with open(fieldSchemaFile, 'r') as csvFile: reader = csv.reader(csvFile, dialect='excel') # Skip the headers header = next(reader) # Read all the rows and add fields accordingly fieldName = None for line in reader: fieldType = Utility.fieldTypeLookup(line[1]) # Add a line as a new field if this is the first occurence of that "field" if line[0] != fieldName: addAField(featureClass, fieldType, line) fieldName = line[0] # Set the domain for the field, including subtype code if necessary if bool(line[5]): if bool(line[8]): arcpy.AssignDomainToField_management( featureClass, line[0], line[5], line[8] + ": " + subTypes[line[8]]) else: if len(subTypes) > 0: subTypeItems = subTypes.items() for subTypeItem in subTypeItems: arcpy.AssignDomainToField_management( featureClass, line[0], line[5], subTypeItem[0] + ": " + subTypeItem[1]) else: arcpy.AssignDomainToField_management( featureClass, line[0], line[5]) # Set the default value for the field if bool(line[6]): defaultValue = line[6] castedDefault = castValue(fieldType, defaultValue) if bool(line[8]): arcpy.AssignDefaultToField_management( featureClass, line[0], castedDefault, line[8] + ": " + subTypes[line[8]]) else: arcpy.AssignDefaultToField_management( featureClass, line[0], castedDefault) # Check to see if this field sets a subtype and if it does, go create the subtypes if line[7] == "True": subTypes = addSubtypes(schemasFolder, schema, featureClass, line[0]) except Exception as err: arcpy.AddError( traceback.format_exception_only(type(err), err)[0].rstrip()) else: arcpy.AddMessage("Success! - Completed: AddFieldsFromSchema") finally: arcpy.AddMessage("Exiting: AddFieldsFromSchema")
def xu_ly_duong_bo_nuoc(self): arcpy.env.overwriteOutput = 1 # Khai bao bien SongSuoiA = self.duong_dan_nguon + "ThuyHe/SongSuoiA" MatNuocTinh = self.duong_dan_nguon + "ThuyHe/MatNuocTinh" KenhMuongA = self.duong_dan_nguon + "ThuyHe/KenhMuongA" lop_bai_boi = self.duong_dan_nguon + "ThuyHe/BaiBoiA" SongSuoiA_Copy = SongSuoiA + "_Copy" MatNuocTinh_Copy = MatNuocTinh + "_Copy" KenhMuongA_Copy = KenhMuongA + "_Copy" lop_thuy_he_Copy_Agg = SongSuoiA_Copy + "_Agg" lop_thuy_he_Copy_Agg_Tbl = self.duong_dan_nguon + "SongSuoiA_Copy_Agg_Tbl" lop_thuy_he_DuongBoNuoc = SongSuoiA_Copy + "_DuongBoNuoc" arcpy.Snap_edit(lop_bai_boi, [[KenhMuongA, "EDGE", self.khoang_Cach], [MatNuocTinh, "EDGE", self.khoang_Cach], [SongSuoiA, "EDGE", self.khoang_Cach]]) #Append arcpy.CopyFeatures_management(SongSuoiA, SongSuoiA_Copy) arcpy.AddField_management(SongSuoiA_Copy, "LOAI_RANH_GIOI", "LONG", None, None, None, "LOAI_RANH_GIOI", "NULLABLE") arcpy.CalculateField_management(SongSuoiA_Copy, "LOAI_RANH_GIOI", 6, "PYTHON_9.3") arcpy.CopyFeatures_management(MatNuocTinh, MatNuocTinh_Copy) arcpy.AddField_management(MatNuocTinh_Copy, "LOAI_RANH_GIOI", "LONG", None, None, None, "LOAI_RANH_GIOI", "NULLABLE") arcpy.CalculateField_management(MatNuocTinh_Copy, "LOAI_RANH_GIOI", 1, "PYTHON_9.3") arcpy.CopyFeatures_management(KenhMuongA, KenhMuongA_Copy) arcpy.AddField_management(KenhMuongA_Copy, "LOAI_RANH_GIOI", "LONG", None, None, None, "LOAI_RANH_GIOI", "NULLABLE") arcpy.CalculateField_management(KenhMuongA_Copy, "LOAI_RANH_GIOI", 4, "PYTHON_9.3") arcpy.Append_management( [lop_bai_boi, MatNuocTinh_Copy, KenhMuongA_Copy], SongSuoiA_Copy, "NO_TEST", None, None) #AggregatePolygons arcpy.AggregatePolygons_cartography(SongSuoiA_Copy, lop_thuy_he_Copy_Agg, "0.001 Meters", "0 SquareMeters", "0 SquareMeters", "NON_ORTHOGONAL", "", lop_thuy_he_Copy_Agg_Tbl) DM.JoinField(lop_thuy_he_Copy_Agg_Tbl, "INPUT_FID", SongSuoiA_Copy, "OBJECTID", None) #danh dau sông có diện tích lớn nhất trong group rows2 = arcpy.SearchCursor(lop_thuy_he_Copy_Agg_Tbl, sort_fields="OUTPUT_FID A") _outPut_id = 0 _area_max = 0 my_dict = {} for row2 in rows2: if row2.getValue("LOAI_RANH_GIOI") is not None: if _outPut_id == row2.getValue("OUTPUT_FID"): if _area_max < row2.getValue("Shape_Area"): _area_max = row2.getValue("Shape_Area") my_dict[row2.getValue("OUTPUT_FID")] = _area_max else: _area_max = row2.getValue("Shape_Area") my_dict[row2.getValue("OUTPUT_FID")] = _area_max _outPut_id = row2.getValue("OUTPUT_FID") #Update lại bảng join rows_update = arcpy.UpdateCursor(lop_thuy_he_Copy_Agg_Tbl) for row_update in rows_update: if row_update.getValue("LOAI_RANH_GIOI") is None: rows_update.deleteRow(row_update) else: if row_update.getValue("Shape_Area") != my_dict[ row_update.getValue("OUTPUT_FID")]: rows_update.deleteRow(row_update) del row_update del rows_update DM.JoinField(lop_thuy_he_Copy_Agg, "OBJECTID", lop_thuy_he_Copy_Agg_Tbl, "OUTPUT_FID", None) #Xóa bãi bồi trong Aggregate rows_update = arcpy.UpdateCursor(lop_thuy_he_Copy_Agg) for row_update in rows_update: if row_update.getValue("LOAI_RANH_GIOI") is None: rows_update.deleteRow(row_update) del row_update del rows_update #FeatureToLine arcpy.FeatureToLine_management([lop_thuy_he_Copy_Agg], lop_thuy_he_DuongBoNuoc, None, "ATTRIBUTES") #Chỉnh sửa lại field arcpy.DeleteField_management(lop_thuy_he_DuongBoNuoc, [ "FID_SongSuoiA_Copy2_Agg", "OUTPUT_FID", "INPUT_FID", "loaiTrangThaiNuocMat", "ten", "doRong", "SongSuoiA_Rep_ID", "SongSuoiA_Rep_OVERRIDE", "RuleID", "Override", "Shape_Length_1", "Shape_Area_1", "loaiTrangThaiDuongBoNuoc", "loaiRanhGioiNuocMat" ]) arcpy.AddField_management(lop_thuy_he_DuongBoNuoc, "loaiTrangThaiDuongBoNuoc", "SHORT", None, None, None, "Loai trang thai duong bo nuoc", "NULLABLE", None, "LoaiTrangThaiDuongBoNuoc") arcpy.AddField_management(lop_thuy_he_DuongBoNuoc, "loaiRanhGioiNuocMat", "LONG", None, None, None, "Loai ranh gioi nuoc mat", "NULLABLE", None, "LoaiRanhGioiNuocMat") arcpy.CalculateField_management(lop_thuy_he_DuongBoNuoc, "loaiTrangThaiDuongBoNuoc", 1, "PYTHON_9.3") arcpy.CalculateField_management(lop_thuy_he_DuongBoNuoc, "loaiRanhGioiNuocMat", "!LOAI_RANH_GIOI!", "PYTHON_9.3") arcpy.AssignDefaultToField_management(lop_thuy_he_DuongBoNuoc, "maDoiTuong", "LG01", None) arcpy.CalculateField_management(lop_thuy_he_DuongBoNuoc, "maDoiTuong", "'LG01'", "PYTHON_9.3") arcpy.DeleteField_management(lop_thuy_he_DuongBoNuoc, ["LOAI_RANH_GIOI"]) DuongBoNuoc_Path = self.duong_dan_nguon + "ThuyHe/DuongBoNuoc" if int(arcpy.GetCount_management(DuongBoNuoc_Path).getOutput(0)) > 0: arcpy.DeleteFeatures_management(DuongBoNuoc_Path) duongBoNuocFields = [ "SHAPE@", "maNhanDang", "ngayThuNhan", "ngayCapNhat", "maDoiTuong", "loaiTrangThaiDuongBoNuoc", "loaiRanhGioiNuocMat", "nguonDuLieu", "maTrinhBay", "tenManh", "soPhienHieuManhBanDo" ] duongBoNuocFields2 = [ "SHAPE@", "maNhanDang", "ngayThuNhan", "ngayCapNhat", "maDoiTuong", "loaiTrangThaiDuongBoNuoc", "loaiRanhGioiNuocMat", "nguonDuLieu", "maTrinhBay", "tenManh", "soPhienHieuManhBanDo", "DuongBoNuoc_Rep_ID" ] with arcpy.da.SearchCursor(lop_thuy_he_DuongBoNuoc, duongBoNuocFields) as sCur: with arcpy.da.InsertCursor(DuongBoNuoc_Path, duongBoNuocFields2) as iCur: for sRow in sCur: iCur.insertRow([ sRow[0], sRow[1], sRow[2], sRow[3], sRow[4], sRow[5], sRow[6], sRow[7], sRow[8], sRow[9], sRow[10], 1 ]) arcpy.CopyFeatures_management( DuongBoNuoc_Path, self.duong_dan_dich + "ThuyHe/DuongBoNuoc")
def validarGDB(gdb): informacion = [] desc = arcpy.Describe(gdb) validacion = desc.basename if validacion[0:10] == 'BD_SEGM_R_': if arcpy.Exists(r'{}\Procesamiento'.format(gdb)): ubigeo = validacion[10:16] dataset = r'{}\Procesamiento'.format(gdb) if arcpy.Exists(r'{}\CCPPRUTAS_{}'.format(dataset, ubigeo)): ccppsRuta = fcCcppRutas(gdb, ubigeo) rutas = fcRutas(gdb, ubigeo) con01 = consistencia01(ccppsRuta) con02 = consistencia02(rutas, ccppsRuta) if len(con01) > 0 or len(con02) > 0: informacion.extend(con01) informacion.extend(con02) for x in informacion: if x[0] == 1: arcpy.AddWarning( "El ccpp {} no presenta un numero de orden en la ruta" .format(x[1])) elif x[0] == 2: arcpy.AddWarning( "La ruta: {} contiene centros poblados en orden NO correlativos" .format(x[1])) elif x[0] == 3: arcpy.AddWarning( "El centro poblado {} no existe en la base de datos (posiblemente agrego un centro poblado nuevo)" .format(x[1])) elif x[0] == 4: arcpy.AddWarning( "El centro poblado {} no se encuentra o fue eliminado, asegurese de que todos los centros poblados RURALES del distrito se encuentren presentes en la Segmentacion" .format(x[1])) else: output = crearFeature(ubigeo, dataset) arcpy.SetParameterAsText(1, output) params = arcpy.GetParameterInfo() for param in params: if '{}'.format(param.name) == 'seccion': param.symbology = lyrScr arcpy.RefreshActiveView() mxd = arcpy.mapping.MapDocument("CURRENT") for i in arcpy.mapping.ListLayers(mxd): if i.name == "SCR_{}".format(ubigeo): i.replaceDataSource(gdb, "FILEGDB_WORKSPACE", "SCR_{}".format(ubigeo), True) arcpy.AssignDefaultToField_management( output, 'UBIGEO', ubigeo) else: arcpy.AddError( "Debes asignar el orden de visita a los centros poblados") else: arcpy.AddError("OBSERVACION:") arcpy.AddError( "No se encuentra el dataset 'Procesamiento' dentro de la GDB ingresada" ) else: arcpy.AddError("El dataset ingresado es incorrecto")
def detruireDomaineAttribut(self, workspace, classe): #------------------------------------------------------------------------------------- """ Permet de détruire tous les domaines existants dans la Géodatabase. Paramètres: ----------- workspace : Nom de la géodatabase ou les domaines seront détruits. classe : Liste des noms de classe contenus dans la géodatabase utilisés pour créer les domaines. """ #Définir le workspace par défaut arcpy.env.workspace = workspace #Extraire les FeatureClass de la Géodatabase for fc in arcpy.ListFeatureClasses(): #Vérifier si la classe est présente dans la liste des classes if fc.upper() in classe: #Afficher le message pour détruire les domaines de la classe traité arcpy.AddMessage(" ") arcpy.AddMessage(u"- Détruire les subtypes de la classe : " + fc) #Définir tous les Subtypes subtypes = arcpy.da.ListSubtypes(fc) #Vérifier si un Subtype est présent if subtypes.values()[0]['SubtypeField'] <> "": #Afficher le message arcpy.AddMessage("SetSubtypeField_management('" + fc + "', #, True)") #Enlever les subtypes d'une classe arcpy.SetSubtypeField_management(fc, "#", True) #Afficher les subtypes #for stcode, stdict in list(subtypes.items()): #Afficher le message #arcpy.AddMessage(" RemoveSubtype_management('" + fc + "', '" + str(stcode) + "')") #Détruire un subtype d'une classe #arcpy.RemoveSubtype_management(fc, stcode) #Afficher le message pour détruire les domaines de la classe traité arcpy.AddMessage(u"- Détruire le domaine et la valeur par défaut pour chaque attribut de la classe : " + fc) #Traiter tous les fields for field in arcpy.ListFields(fc): #Vérifier la présence d'un domaine if field.domain <> "": #Afficher le message arcpy.AddMessage("RemoveDomainFromField_management('" + fc + "', '" + field.name + "')") #Détruire un domaine dans un attribut d'une classe arcpy.RemoveDomainFromField_management(fc, field.name) #Vérifier si une valeur par défaut est présente if field.defaultValue <> None: #Afficher le message arcpy.AddMessage("AssignDefaultToField_management('" + fc + "', '" + field.name + "' # # True)") #Détruire la valeur par défaut de l'attribut d'une classe arcpy.AssignDefaultToField_management(fc, field.name, "#", "#", True) #Extraire les tables de la Géodatabase for tbl in arcpy.ListTables(): #Vérifier si la table est présente dans la liste des classes if tbl.upper() in classe: #Afficher le message pour détruire les domaines de la classe traité arcpy.AddMessage(" ") arcpy.AddMessage(u"- Détruire les subtypes de la table : " + tbl) #Définir tous les Subtypes subtypes = arcpy.da.ListSubtypes(tbl) #Vérifier si un Subtype est présent if subtypes.values()[0]['SubtypeField'] <> "": #Afficher le message arcpy.AddMessage("SetSubtypeField_management('" + tbl + "', #, True)") #Enlever les subtypes d'une classe arcpy.SetSubtypeField_management(tbl, "#", True) #Afficher les subtypes #for stcode, stdict in list(subtypes.items()): #Afficher le message #arcpy.AddMessage(" RemoveSubtype_management('" + tbl + "', '" + str(stcode) + "')") #Détruire un subtype d'une table #arcpy.RemoveSubtype_management(tbl, stcode) #Afficher le message pour détruire les domaines de la classe traité arcpy.AddMessage(u"- Détruire le domaine et la valeur par défaut pour chaque attribut de la table : " + tbl) #Traiter tous les fields for field in arcpy.ListFields(tbl): #Vérifier la présence d'un domaine if field.domain <> "": #Afficher le message arcpy.AddMessage("RemoveDomainFromField_management('" + tbl + "', '" + field.name + "')") #Détruire un domaine dans un attribut d'une classe arcpy.RemoveDomainFromField_management(tbl, field.name) #Vérifier si une valeur par défaut est présente if field.defaultValue <> None: #Afficher le message arcpy.AddMessage("AssignDefaultToField_management('" + tbl + "', '" + field.name + "' # # True)") #Détruire la valeur par défaut de l'attribut d'une table arcpy.AssignDefaultToField_management(tbl, field.name, "#", "#", True) #Envoyer un message arcpy.AddMessage(" ") arcpy.AddMessage(u"- Détruire les domaines non-utilisés dans la Géodatabase") #Extraire la description de la Géodatabase desc = arcpy.Describe(workspace) #Extraire tous les domaines existants de la Géodatabase domains = desc.domains #Traiter tous les domaines for domain in domains: try: #Détruire un domaine arcpy.DeleteDomain_management(workspace, domain) #Afficher le message arcpy.AddMessage("DeleteDomain_management('" + workspace + "', '" + domain + "')") #Gestion des erreurs except Exception, err: #Afficher l'erreur arcpy.AddWarning(u"Le domaine est encore utilisé et ne peut être détruit : " + domain)
arcpy.AddError( "Kolom PRFL_Opmerkingen bestaat al! Controleer zelf of type en length juist zijn." ) try: arcpy.AddMessage("Kolom Opmerkingen_ProfielMaken toevoegen...") arcpy.AddField_management(VakFC, "Opmerkingen_ProfielMaken", "TEXT", "", "", 250) except: arcpy.AddError( "Kolom Opmerkingen_ProfielMaken bestaat al! Controleer zelf of type en length juist zijn." ) #------------ # default value aan de ruwheids kolommen zetten. Alles op 1 arcpy.AssignDefaultToField_management(in_table=VakFC, field_name="Ruw_BuiTal_1", default_value="1", subtype_code="", clear_value="false") arcpy.AssignDefaultToField_management(in_table=VakFC, field_name="Ruw_BuiTal_2", default_value="1", subtype_code="", clear_value="false") arcpy.AssignDefaultToField_management(in_table=VakFC, field_name="Ruw_BuiTal_3", default_value="1", subtype_code="", clear_value="false") arcpy.AssignDefaultToField_management(in_table=VakFC, field_name="Ruw_BuiTal_4", default_value="1",