Python arcpy.GetCount_management() Examples

The following are 11 code examples of arcpy.GetCount_management(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module arcpy , or try the search function .
Example #1
Source File: arcapi_test.py    From arcapi with GNU Lesser General Public License v3.0 7 votes vote down vote up
def testto_points(self):
        obs = 10
        wc = '"OBJECTID" < ' + str(obs + 1)
        ofc = arcpy.CreateScratchName("tmp_out.dbf", workspace="c:\\temp").replace('.dbf', '.shp')
        cs = 27700
        ptfc = ap.to_points(self.t_fc, ofc, "POP_EST", "GDP_MD_EST", cs, w = wc)
        est = int(arcpy.GetCount_management(ptfc).getOutput(0))
        arcpy.Delete_management(ptfc)
        self.assertEqual(est, obs)
        pass


##    def testwsp(self):
##        pass
##
##    def testswsp(self):
##        pass 
Example #2
Source File: _data_objects.py    From registrant with MIT License 6 votes vote down vote up
def get_attachments_count(self):
        """Get number of attachments stored for a table/feature class."""
        rel_classes = [
            os.path.join(self.root, rc)
            for rc in getattr(self._desc, 'relationshipClassNames', [''])
        ]
        for rc in rel_classes:
            rc_desc = arcpy.Describe(rc)
            if rc_desc.isAttachmentRelationship:
                return int(
                    arcpy.GetCount_management(
                        os.path.join(
                            self.root,
                            rc_desc.destinationClassNames[0])).getOutput(0))

    # ---------------------------------------------------------------------- 
Example #3
Source File: Layer_to_KML_attachment.py    From sample-gp-tools with Apache License 2.0 5 votes vote down vote up
def checks(inputFeatures):
  """ Pre checks to make sure we can run """

  def hasAttachments(inputFeatures):

    d = arcpy.Describe(inputFeatures)
    rc_names = d.relationshipClassNames

    if len(rc_names) > 0:
      for rc_name in rc_names:
        # relationship class is always beside the input features
        rc = os.path.join(d.path, rc_name)
        rcDesc = arcpy.Describe(rc)

        if rcDesc.isAttachmentRelationship:
          attachTables = rcDesc.destinationClassNames
          if len(attachTables) > 0:
            for att_tableName in attachTables:
              if arcpy.Exists(os.path.join(d.path, att_tableName)):
                # assume the attachment table resides beside the input feature
                return os.path.join(d.path, att_tableName)
              else:
                # if the attachment table is not found, walk through the workspace looking for it
                for dirpath, dirnames, filenames in arcpy.da.Walk(ws, datatype="Table"):
                  for f in filenames:
                    if f == att_tableName:
                      if arcpy.Exists(os.path.join(dirpath, att_tableName)):
                        return os.path.join(dirpath, att_tableName)

    return None

  ## find the attachment table
  attachTable = hasAttachments(inputFeatures)

  ## check for sequential OIDs
  seq = True
  if max([row[0] for row in arcpy.da.SearchCursor(inputFeatures,["OID@"])]) != \
     int(arcpy.GetCount_management(inputFeatures).getOutput(0)):
    seq = False

  return attachTable, seq 
Example #4
Source File: s57_2_chart.py    From maritime-charting-sample-scripts with Apache License 2.0 5 votes vote down vote up
def maskCoastlineConflicts(prod_db, desktop_fldr):
    arcpy.AddMessage("\tMasking coastline and bridges")
    # Subtype field used in where clause to access bridges in CulturalFeaturesA
    subtype_fld = arcpy.AddFieldDelimiters(prod_db, "FCSubtype")
    # Get subtype of Bridge
    bridge = "5"
    # Define spatial reference
    sr = arcpy.SpatialReference(4326)

    # Get CoastlineL and CulturalFeaturesA layers
    coastlinel_fc = getFC(prod_db, "CoastlineL", NAUT_FDS)
    culturalfeaturesa_fc = getFC(prod_db, "CulturalFeaturesA", NAUT_FDS)

    # Only continue if CoastlineL and CulturalFeaturesA layers are in the TOC
    if coastlinel_fc != "" and culturalfeaturesa_fc != "":
        # Make feature layer form CoastlineL
        arcpy.MakeFeatureLayer_management(coastlinel_fc, "coastlinel_lyr")
        # Make feature layer of bridge features
        where = subtype_fld + " = " + bridge
        arcpy.MakeFeatureLayer_management(culturalfeaturesa_fc, "bridges", where)
        # Check if there are any bridge features in the layer
        if int(arcpy.GetCount_management("bridges").getOutput(0)) > 0:
            # Run Intersecting Layers Mask GP tool to create mask poly where coastline intersect bridges
            mask_fc = os.path.join(prod_db, CARTO_FDS, "MASK_CoastlineL")
            arcpy.IntersectingLayersMasks_cartography("bridges", "coastlinel_lyr", mask_fc, REF_SCALE, sr, "0.01 POINTS")

    return 
Example #5
Source File: arcapi_test.py    From arcapi with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testtlist_to_table(self):
        colnames = ['NAME', 'POP_EST']
        coltypes = ['TEXT', 'DOUBLE']
        collengths = [250, '#']
        coldefs = zip(colnames, coltypes, collengths)
        coldefs2 = ['NAME:TEXT', 'POP_EST:DOUBLE']

        # read data
        tl = []
        with arcpy.da.SearchCursor(self.t_fc, colnames) as sc:
            for row in sc:
                tl.append(tuple(row))

        # write as table using log column definition
        ot = arcpy.CreateScratchName('tmp.dbf', workspace='c:\\temp')
        ot = ap.tlist_to_table(tl, ot, coldefs, -9, 'nullText')
        est1 = int(arcpy.GetCount_management(ot).getOutput(0))

        # write as table using short column definition
        ot = arcpy.CreateScratchName('tmp.dbf', workspace='c:\\temp')
        ot = ap.tlist_to_table(tl, ot, coldefs2, -9, 'nullText')
        est2 = int(arcpy.GetCount_management(ot).getOutput(0))
        obs = int(arcpy.GetCount_management(self.t_fc).getOutput(0))

        arcpy.Delete_management(ot)
        self.assertTrue(all((est1 == obs, est2 == obs)))
        pass

##    def testdocu(self):
##        pass 
Example #6
Source File: arcapi.py    From arcapi with GNU Lesser General Public License v3.0 5 votes vote down vote up
def nrow(x):
    """Return number of rows in a table as integer.

    Required:
    x -- input table or table view

    Example:
    >>> nrow('c:\\foo\\bar.shp')
    """
    return int(arcpy.GetCount_management(x).getOutput(0)) 
Example #7
Source File: _data_objects.py    From registrant with MIT License 5 votes vote down vote up
def get_row_count(self):
        """Get number of rows in geodatabase table."""
        return int(arcpy.GetCount_management(self.path).getOutput(0))


######################################################################## 
Example #8
Source File: s57_2_chart.py    From maritime-charting-sample-scripts with Apache License 2.0 4 votes vote down vote up
def cartoLimits(aoi, prod_db, desktop_fldr):
    # Subtype field used in where clause to filter inputs to Model
    subtype_fld = arcpy.AddFieldDelimiters(prod_db, "FCSubtype")

    # Make feature layer of aoi
    arcpy.MakeFeatureLayer_management(aoi, "aoi")
    # Convert AOI to polyline
    aoi_line = os.path.join(arcpy.env.scratchGDB, "aoi_line")
    arcpy.FeatureToLine_management("aoi", aoi_line)
    arcpy.MakeFeatureLayer_management(aoi_line, "aoi_line")

    # Get list of input feature classes, subtypes, and cart limit feature classes
    inputs = [["DangersA", [], "DangersA_L"],
              ["DepthsA", ["5", "10", "15"], "DepthsA_L"],
              ["IceFeaturesA", [], "IceA_L"],
              ["MilitaryFeaturesA", [], "MilitaryA_L"],
              ["NaturalFeaturesA", ["1", "20", "35"], "NaturalA_L"],
              ["OffshoreInstallationsA", [], "OffshoreA_L"],
              ["PortsAndServicesA", ["5", "10", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "80"], "PortsA_L"],
              ["RegulatedAreasAndLimitsA", ["1", "5", "10", "15", "20", "30", "40", "50", "60", "65", "70", "75", "85", "95", "105", "110", "115"], "RegulatedA_L"],
              ["SeabedA", ["15"], "SeabedA_L"],
              ["TracksAndRoutesA", ["1", "5", "10", "15", "20", "25", "40", "45", "70"], "TracksA_L"]]

    # Set workspace
    arcpy.env.workspace = prod_db

    # Get CoastlineA and CloastlineL layers
    coastlinea_fc = getFC(prod_db, "CoastlineA", NAUT_FDS)
    arcpy.MakeFeatureLayer_management(coastlinea_fc, "CoastlineA")
    coastlinel_fc = getFC(prod_db, "CoastlineL", NAUT_FDS)
    arcpy.MakeFeatureLayer_management(coastlinel_fc, "CoastlineL")

    # Loop through list of inputs
    for data in inputs:
        # Get full paths to data
        input_fc = getFC(prod_db, data[0], NAUT_FDS)
        output_fc = getFC(prod_db, data[2], CARTO_FDS)
        if input_fc != "" and output_fc != "":
            # Check if there are subtypes, if there are, write where clause
            where = ""
            if len(data[1]) > 0:
                where = subtype_fld + " = "
                where = where + (" OR " + subtype_fld + " = ").join(data[1])
                # Remove single quotes that get added to beginning and end of where clause
                where = where.replace("'", "")
            # Select features in where clause
            arcpy.MakeFeatureLayer_management(input_fc, "in_lyr", where)
            # Only run Generate Cartographic Limits model if layer has features
            if int(arcpy.GetCount_management("in_lyr").getOutput(0)) > 0:
                arcpy.AddMessage("\t\t" + data[2])
                arcpy.GenerateCartographicLimits_nautical("in_lyr", "CoastlineL; CoastlineA; aoi_line", output_fc)

    return 
Example #9
Source File: SSURGO_CheckgSSURGO2.py    From geo-pit with GNU General Public License v2.0 4 votes vote down vote up
def GetGDBCount(theInputDB, dSDMCounts, areaSym):
    # Get record count from gSSURGO database
    # Only those soil attributes present in the SDM database will be checked
    # Some metadata and sdv tables are not found in SDM
    try:
        dGDBCounts = dict()
        env.workspace = theInputDB
        badCount = list()
        PrintMsg(" \n\t\tGetting record count from gSSURGO tables", 0)
        arcpy.SetProgressor("step", "Getting table record count from " + os.path.basename(theInputDB), 1, len(dSDMCounts), 1)

        tblList = sorted(dSDMCounts)

        for tbl in tblList:
            arcpy.SetProgressorLabel(tbl)
            sdmCnt = dSDMCounts[tbl]

            if arcpy.Exists(tbl):
                gdbCnt = int(arcpy.GetCount_management(os.path.join(theInputDB, tbl)).getOutput(0))

            else:
                raise MyError, "Missing table (" + tbl+ ") in " + os.path.basename(theInputDB)
                badCount.append((os.path.join(theInputDB, tbl), 0, sdmCnt))

            dGDBCounts[tbl] = gdbCnt
            arcpy.SetProgressorPosition()

            if sdmCnt != gdbCnt:
                if sdmCnt == -1:
                    # SDA query failed to get count for this table
                    badCount.append((tbl, 0, gdbCnt, gdbCnt))

                else:
                    # Record counts do not agree
                    badCount.append(( tbl, sdmCnt, gdbCnt, (sdmCnt - gdbCnt) ))

        if len(badCount) > 0:
            PrintMsg("\t\tDiscrepancy found in table counts:", 2)
            PrintMsg(" \nTABLE, SDM, GDB, DIFF", 0)

        for tbl in badCount:
            PrintMsg(tbl[0] + ", " + str(tbl[1]) + ", " + str(tbl[2]) + ", " + str(tbl[3]), 0)

        arcpy.SetProgressorLabel("")
        arcpy.ResetProgressor()

        if len(badCount) > 0:
            return False

        else:
            return True

    except MyError, e:
        # Example: raise MyError, "This is an error message"
        PrintMsg(str(e), 2)
        return False 
Example #10
Source File: SSURGO_CheckgSSURGO.py    From geo-pit with GNU General Public License v2.0 4 votes vote down vote up
def GetGDBCount(theInputDB, dSDMCounts):
    # Get record count from gSSURGO database
    # Only those soil attributes present in the SDM database will be checked
    # Some metadata and sdv tables are not found in SDM
    try:
        dGDBCounts = dict()
        env.workspace = theInputDB
        badCount = list()
        PrintMsg(" \n\t\tGetting record count from gSSURGO tables", 0)
        arcpy.SetProgressor("step", "Getting table record count from " + os.path.basename(theInputDB), 1, len(dSDMCounts), 1)

        tblList = sorted(dSDMCounts)

        for tbl in tblList:
            arcpy.SetProgressorLabel(tbl)
            sdmCnt = dSDMCounts[tbl]

            if arcpy.Exists(tbl):
                gdbCnt = int(arcpy.GetCount_management(os.path.join(theInputDB, tbl)).getOutput(0))

            else:
                raise MyError, "Missing table (" + tbl+ ") in " + os.path.basename(theInputDB)
                badCount.append((os.path.join(theInputDB, tbl), 0, sdmCnt))

            dGDBCounts[tbl] = gdbCnt
            arcpy.SetProgressorPosition()

            if sdmCnt != gdbCnt:
                if sdmCnt == -1:
                    # SDA query failed to get count for this table
                    badCount.append((tbl, 0, gdbCnt, gdbCnt))

                else:
                    # Record counts do not agree
                    badCount.append(( tbl, sdmCnt, gdbCnt, (sdmCnt - gdbCnt) ))

        if len(badCount) > 0:
            PrintMsg("\t\tDiscrepancy found in table counts:", 2)
            PrintMsg(" \nTABLE, SDM, GDB, DIFF", 0)

        for tbl in badCount:
            PrintMsg(tbl[0] + ", " + str(tbl[1]) + ", " + str(tbl[2]) + ", " + str(tbl[3]), 0)

        arcpy.SetProgressorLabel("")
        arcpy.ResetProgressor()

        if len(badCount) > 0:
            return False

        else:
            return True

    except MyError, e:
        # Example: raise MyError, "This is an error message"
        PrintMsg(str(e), 2)
        return False 
Example #11
Source File: gSSURGO_ValuTable.py    From geo-pit with GNU General Public License v2.0 4 votes vote down vote up
def MakeNCCPIQueryTable(inputDB, qTable):
    # create query table containing information from component and chorizon tables
    # return name of querytable. Failure returns an empty string for the table name.
    #
    # COINTERP.RULENAME CHOICES:
    #
    # 'NCCPI - National Commodity Crop Productivity Index (Ver 2.0)'
    # 'NCCPI - NCCPI Corn and Soybeans Submodel (II)'
    # 'NCCPI - NCCPI Cotton Submodel (II)'
    # 'NCCPI - NCCPI Small Grains Submodel (II)'
    #

    try:

        # Join chorizon table with component table
        inTables = [os.path.join(inputDB, "component"), os.path.join(inputDB, "cointerp")]

        # interphr is the fuzzy value
        theFields = [["COMPONENT.MUKEY", "MUKEY"], \
        ["COMPONENT.COKEY", "COKEY"], \
        ["COMPONENT.COMPPCT_R", "COMPPCT_R"], \
        ["COINTERP.RULENAME", "RULENAME"], \
        ["COINTERP.RULEDEPTH", "RULEDEPTH"], \
        ["COINTERP.INTERPHR", "INTERPHR"]]

        rule = 'NCCPI - National Commodity Crop Productivity Index (Ver 2.0)'
        theSQL = "COMPONENT.COMPPCT_R > 0 AND COMPONENT.MAJCOMPFLAG = 'Yes' AND COMPONENT.COKEY = COINTERP.COKEY  AND COINTERP.MRULENAME = '" + rule + "'"
        PrintMsg(" \nCalculating NCCPI weighted averages for all major components...", 0)

        # Things to be aware of with MakeQueryTable:
        # USE_KEY_FIELDS does not create OBJECTID field. Lack of OBJECTID precludes sorting on Mukey.
        # ADD_VIRTUAL_KEY_FIELD creates OBJECTID, but qualifies field names using underscore (eg. COMPONENT_COKEY)
        #
        arcpy.MakeQueryTable_management(inTables, qTable, "ADD_VIRTUAL_KEY_FIELD","",theFields, theSQL)

        if arcpy.Exists(qTable):
            iCnt = int(arcpy.GetCount_management(qTable).getOutput(0))
            if iCnt == 0:
                raise MyError, "Failed to retrieve NCCPI data"

        return True

    except MyError, e:
        # Example: raise MyError("this is an error message")
        PrintMsg(str(e) + " \n", 2)
        return False