當前位置: 首頁>>代碼示例>>Python>>正文


Python arcpy.Exists方法代碼示例

本文整理匯總了Python中arcpy.Exists方法的典型用法代碼示例。如果您正苦於以下問題:Python arcpy.Exists方法的具體用法?Python arcpy.Exists怎麽用?Python arcpy.Exists使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在arcpy的用法示例。


在下文中一共展示了arcpy.Exists方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: populate_restrictions_and_impedances

# 需要導入模塊: import arcpy [as 別名]
# 或者: from arcpy import Exists [as 別名]
def populate_restrictions_and_impedances(param_ND, param_restrictions, param_impedances):
    '''Populate the restrictions and impdance attribute parameters with filter lists
    based on the chosen network dataset'''
    if param_ND.altered:
        inNADataset = param_ND.value
        if arcpy.Exists(inNADataset):
            desc = arcpy.Describe(inNADataset)
            atts = desc.attributes
            restrictions = []
            impedances = []
            # Cycle through the attributes, find the restrictions and impedances,
            # and add the names to the arrays.
            for att in atts:
                if att.usageType == "Restriction":
                    restrictions.append(att.name)
                elif att.usageType == "Cost":
                    impedances.append(att.name + " (Units: " + att.units + ")")
            # Put the value list of restrictions into the GUI field.
            param_restrictions.filter.list = sorted(restrictions)
            param_impedances.filter.list = sorted(impedances) 
開發者ID:Esri,項目名稱:public-transit-tools,代碼行數:22,代碼來源:ToolValidator.py

示例2: getNetworkGraph

# 需要導入模塊: import arcpy [as 別名]
# 或者: from arcpy import Exists [as 別名]
def getNetworkGraph(segments,segmentlengths):
    """
    Builds a networkx graph from the network file, inluding segment length taken from arcpy.
    It selects the largest connected component of the network (to prevent errors from routing between unconnected parts)
    """
    #generate the full network path for GDAL to be able to read the file
    path =str(os.path.join(arcpy.env.workspace,segments))
    print path
    if arcpy.Exists(path):
        g = nx.read_shp(path)
        #This selects the largest connected component of the graph
        sg = list(nx.connected_component_subgraphs(g.to_undirected()))[0]
        print "graph size (excluding unconnected parts): "+str(len(g))
        # Get the length for each road segment and append it as an attribute to the edges in the graph.
        for n0, n1 in sg.edges():
            oid = sg[n0][n1]["OBJECTID"]
            sg[n0][n1]['length'] = segmentlengths[oid]
        return sg
    else:
        print "network file not found on path: "+path 
開發者ID:simonscheider,項目名稱:mapmatching,代碼行數:22,代碼來源:mapmatcher.py

示例3: getSegmentInfo

# 需要導入模塊: import arcpy [as 別名]
# 或者: from arcpy import Exists [as 別名]
def getSegmentInfo(segments):
    """
    Builds a dictionary for looking up endpoints of network segments (needed only because networkx graph identifies edges by nodes)
    """
    if arcpy.Exists(segments):
        cursor = arcpy.da.SearchCursor(segments, ["OBJECTID", "SHAPE@"])
        endpoints = {}
        segmentlengths = {}
        for row in cursor:
              endpoints[row[0]]=((row[1].firstPoint.X,row[1].firstPoint.Y), (row[1].lastPoint.X, row[1].lastPoint.Y))
              segmentlengths[row[0]]= row[1].length
        del row
        del cursor
        print "Number of segments: "+ str(len(endpoints))
        #prepare segment layer for fast search
        arcpy.Delete_management('segments_lyr')
        arcpy.MakeFeatureLayer_management(segments, 'segments_lyr')
        return (endpoints,segmentlengths)
    else:
        print "segment file does not exist!" 
開發者ID:simonscheider,項目名稱:mapmatching,代碼行數:22,代碼來源:mapmatcher.py

示例4: generate_report

# 需要導入模塊: import arcpy [as 別名]
# 或者: from arcpy import Exists [as 別名]
def generate_report(verbose_mode, property_list, user_files):
    """ Generates the report containing each file and its associated 
        Describe-object attributes. Report is a dictionary and can be useful
        for other scripts.
    """
    report_results = {}
    report_path = open(os.path.join(os.getcwd(), u'Describe Report.txt'), 'wt')
    for f in user_files:
        if arcpy.Exists(f):
            desc_dict = od()
            for d_class in sorted(property_list):
                desc_dict[d_class] = {}
                for p in properties[d_class]:
                    try:
                        desc_dict[d_class][p] = eval("arcpy.Describe(f).{0}".format(p))
                    except AttributeError:
                        if verbose_mode:
                            desc_dict[d_class][p] = 'ATTRIBUTE ERROR: Method not found'
                        else:
                            pass
            report_results[f] = desc_dict
        else:
            report_results[f] = 'FILE NOT FOUND'
    pprint(report_results, report_path, width=400) 
開發者ID:arcpy,項目名稱:sample-gp-tools,代碼行數:26,代碼來源:describe_reporter.py

示例5: _CheckCreateGDBProcess

# 需要導入模塊: import arcpy [as 別名]
# 或者: from arcpy import Exists [as 別名]
def _CheckCreateGDBProcess(self):
        try:
            # If user param is to overwrite GDB, then delete it first
            if self.overWrite.upper() == "YES":
                if arcpy.Exists(self.end_db)==True:
                    arcpy.Delete_management(self.end_db)
                    self.overWrite = None
                    print "Deleted previous GDB {0}".format(self.end_db)
             
            # if the local gdb doesn't exist, then create it using the path and name given in the end_db string
            if arcpy.Exists(self.end_db)==False:
                if self.end_db.rfind("\\") != -1:    
                    lastSlash = self.end_db.rfind("\\")
                else:
                    lastSlash = self.end_db.rfind("/")           
                arcpy.CreateFileGDB_management(self.end_db[:lastSlash], self.end_db[lastSlash+1:])
                self.overWrite = None
                print "Created geodatabase {0}".format(self.end_db[lastSlash+1:])
            else:
                self.overWrite = None
                #print "Geodatabase already exists" 
            return True 
        except:
            print "Unexpected error create geodatabase:", sys.exc_info()[0]
            return False 
開發者ID:Esri,項目名稱:utilities-solution-data-automation,代碼行數:27,代碼來源:dataprep.py

示例6: testdlt

# 需要導入模塊: import arcpy [as 別名]
# 或者: from arcpy import Exists [as 別名]
def testdlt(self):
        est = []
        wc = '"OBJECTID" < 11'
        lr = arcpy.management.MakeFeatureLayer(self.t_fc, "lr", wc).getOutput(0)
        # TODO: test for deleting layers won't pass even though ap.dlt works
        #print lr
        #print arcpy.Exists(lr)
        tempfc = 'in_memory\\tmp'
        if arcpy.Exists(tempfc):
            arcpy.Delete_management(tempfc)
        tmpfc = arcpy.CopyFeatures_management(lr, tempfc).getOutput(0)
        tempshp = arcpy.CreateScratchName('tmp.dbf', workspace='c:\\temp').replace('.dbf', '.shp')
        fc = arcpy.CopyFeatures_management(tmpfc, tempshp).getOutput(0)
        ap.dlt(lr)
        est.append(ap.dlt(tmpfc))
        est.append(ap.dlt(fc))
        est.append(ap.dlt('this does not exist'))
        self.assertEquals(est, [True, True, False])
        pass 
開發者ID:NERC-CEH,項目名稱:arcapi,代碼行數:21,代碼來源:arcapi_test.py

示例7: testadd_fields_from_table

# 需要導入模塊: import arcpy [as 別名]
# 或者: from arcpy import Exists [as 別名]
def testadd_fields_from_table(self):
        fc = os.path.join(self.testing_gdb, 'Illinois')
        copy = fc + '_copy'
        if arcpy.Exists(copy):
            arcpy.Delete_management(copy)
        arcpy.CopyFeatures_management(fc, copy)
        flds = ['POP1990', 'POP2000']
        tab = fc = os.path.join(self.testing_gdb, 'Illinois_county_info')
        ap.add_fields_from_table(copy, tab, flds)
        est = [f.name for f in arcpy.ListFields(copy)]
        try:
            arcpy.Delete_management(copy)
        except: pass
        for f in flds:
            self.assertTrue(f in est)
        pass 
開發者ID:NERC-CEH,項目名稱:arcapi,代碼行數:18,代碼來源:arcapi_test.py

示例8: testjoin_using_dict

# 需要導入模塊: import arcpy [as 別名]
# 或者: from arcpy import Exists [as 別名]
def testjoin_using_dict(self):
        if arcpy.Exists(r'in_memory\copy'):
            arcpy.Delete_management(r'in_memory\copy')
        fc = os.path.join(self.testing_gdb, 'Illinois')
        copy = fc + '_copy'
        if arcpy.Exists(copy):
            arcpy.Delete_management(copy)
        arcpy.CopyFeatures_management(fc, copy)
        flds = ['POP1990', 'POP2000']
        tab = fc = os.path.join(self.testing_gdb, 'Illinois_county_info')
        ap.join_using_dict(copy, 'CNTY_FIPS', tab, 'CNTY_FIPS', flds)
        est = [f.name for f in arcpy.ListFields(copy)]
        try:
            arcpy.Delete_management(copy)
        except: pass
        for f in flds:
            self.assertTrue(f in est)
        pass 
開發者ID:NERC-CEH,項目名稱:arcapi,代碼行數:20,代碼來源:arcapi_test.py

示例9: testconcatenate_fields

# 需要導入模塊: import arcpy [as 別名]
# 或者: from arcpy import Exists [as 別名]
def testconcatenate_fields(self):
        if arcpy.Exists(r'in_memory\copy'):
            arcpy.Delete_management(r'in_memory\copy')
        fc = os.path.join(self.testing_gdb, 'Illinois')
        copy = fc + '_copy'
        if arcpy.Exists(copy):
            arcpy.Delete_management(copy)
        arcpy.CopyFeatures_management(fc, copy)
        ap.concatenate_fields(copy, 'FULL', 75, ['NAME', 'STATE_NAME'], ' County, ')
        obs = 'Jo Daviess County, Illinois'
        with arcpy.da.SearchCursor(copy, 'FULL') as rows:
            est = rows.next()[0]
        del rows
        try:
            arcpy.Delete_management(copy)
        except: pass
        self.assertEqual(est, obs)
        pass 
開發者ID:NERC-CEH,項目名稱:arcapi,代碼行數:20,代碼來源:arcapi_test.py

示例10: CheckFeatureClasses

# 需要導入模塊: import arcpy [as 別名]
# 或者: from arcpy import Exists [as 別名]
def CheckFeatureClasses(theWS):
    # Simply make sure that each featureclass is present.
    #
    try:
        PrintMsg(" \n\tChecking for existence of featureclasses", 0)
        env.workspace = theWS
        missingFC = list()
        lFC = ['MUPOLYGON', 'FEATLINE', 'FEATPOINT', 'MULINE', 'SAPOLYGON', 'MUPOINT']

        for fc in lFC:
            if not arcpy.Exists(fc):
                missingFC.append(fc)

        if len(missingFC) > 0:
            PrintMsg("\t" + os.path.basename(theWS) +  " is missing the following gSSURGO featureclasses: " + ", ".join(missingFC), 2)
            return False

        return True

    except:
        errorMsg()
        return False

## =================================================================================== 
開發者ID:ncss-tech,項目名稱:geo-pit,代碼行數:26,代碼來源:SSURGO_CheckgSSURGO2.py

示例11: check_Step1_gdb

# 需要導入模塊: import arcpy [as 別名]
# 或者: from arcpy import Exists [as 別名]
def check_Step1_gdb(param_inGDB, param_day):
    '''Check that the input gbb from Step 1 contains required Step 1 output.'''

    if param_inGDB.altered:
        if ispy3:
            inStep1GDB = str(param_inGDB.value)
        else:
            inStep1GDB = unicode(param_inGDB.value)
        # Check presence of correct gdb contents
        SQLDbase = os.path.join(inStep1GDB, "Step1_GTFS.sql")
        FlatPolys = os.path.join(inStep1GDB, "Step1_FlatPolys")
        InputErrorMessage = "Step 1 geodatabase does not contain the \
required files.  Please choose the correct geodatabase or re-run \
Step 1.  Required files: Step1_GTFS.sql; Step1_FlatPolys"
        if not os.path.exists(SQLDbase):
            SQLDbase = ""
            param_inGDB.setErrorMessage(InputErrorMessage)
        elif not arcpy.Exists(FlatPolys):
            param_inGDB.setErrorMessage(InputErrorMessage)
        else:
            # Check the SQL database has the required tables in it
            if not checkSQLtables(SQLDbase, ["stops", "trips", "stop_times", "StackedPoints"], ["calendar", "calendar_dates"]):
                message = "The SQL database in your input geodatabase from Step 1 does not have the \
correct tables.  Please choose a valid geodatabase generated using Step 1 of the Count Trips in Polygon Buffers \
around Stops tool."
                param_inGDB.setErrorMessage(message)
            else:
                if param_day:
                    check_SQL_for_generic_weekday(param_day, SQLDbase) 
開發者ID:Esri,項目名稱:public-transit-tools,代碼行數:31,代碼來源:ToolValidator.py

示例12: check_ND_not_from_AddGTFS

# 需要導入模塊: import arcpy [as 別名]
# 或者: from arcpy import Exists [as 別名]
def check_ND_not_from_AddGTFS(param_ND):
    '''Throw a warning if the network dataset appears to have been created using the Add GTFS to a Network Dataset toolbox'''
    if param_ND.altered:
        inNADataset = param_ND.value
        if arcpy.Exists(inNADataset):
            desc = arcpy.Describe(inNADataset)
            sources = set([src.name for src in desc.sources])
            # Source feature class names typical of a network created with the Add GTFS to a Network Dataset toolbox
            AddGTFSSources = set(["Stops", "TransitLines", "Connectors_Stops2Streets", "Stops_Snapped2Streets", "Streets_UseThisOne"])
            if AddGTFSSources.issubset(sources):
                param_ND.setWarningMessage("This network dataset appears to have been created using the Add GTFS to a Network Dataset tool. \
You should not use a network dataset created with that tool because BetterBusBuffers will handle the GTFS data separately. Please choose a \
network dataset appropriate for modeling pedestrians walking along streets and paths.") 
開發者ID:Esri,項目名稱:public-transit-tools,代碼行數:15,代碼來源:ToolValidator.py

示例13: populate_UniqueID

# 需要導入模塊: import arcpy [as 別名]
# 或者: from arcpy import Exists [as 別名]
def populate_UniqueID(param_points, param_UniqueID):
    '''Populate the filter list of potential Unique ID fields for the chosen points fc'''

    # Fields of other types (like doubles) are not acceptable as a UniqueID field
    acceptable_field_types = ["GlobalID", "Guid", "Integer", "OID", "SmallInteger", "String"]
    if param_points.altered:
        # param_points is the user-entered locations dataset
        inLocs = param_points.value
        if arcpy.Exists(inLocs):
            desc = arcpy.Describe(inLocs)
            fieldnames = [f.name for f in desc.fields if f.type in acceptable_field_types]
            # Put the value list of field names into the GUI field.
            param_UniqueID.filter.list = fieldnames 
開發者ID:Esri,項目名稱:public-transit-tools,代碼行數:15,代碼來源:ToolValidator.py

示例14: create_percent_access_polys

# 需要導入模塊: import arcpy [as 別名]
# 或者: from arcpy import Exists [as 別名]
def create_percent_access_polys(raw_cell_counts, percents, out_fc, fields_to_preserve, scratch_workspace):
    '''For each percent threshold, dissolve the cells where the number of times reached exceeds the threshold. Each
    threshold gets its own polygon, and they are all output to the same feature class.
    Params:
    raw_cell_counts: Feature class of cell-like polygons with counts generated from create_raw_cell_counts_fc()
    count_field: The field in raw_cell_counts containing the number of times the cell was reached
    percents: List of percents to calculate results for. Example: 80 means crate a polygon representing the area that
        could be reached for at least 80% of start times.
    num_time_steps: The total number of time steps present in the input time lapse polygon dataset
    out_fc: Path of the output feature class for storing the percent access polygons
    '''

    first = True
    temp_out_dissolve_fc = os.path.join(scratch_workspace, "Temp_" + guid + "_Dissolve")
    for percent in sorted(percents):

        # Select all the cells where the number of times with access is >= our percent threshold
        # The result is all the cells that are reachable at least X% of start times
        query = arcpy.AddFieldDelimiters(raw_cell_counts, "Percent") + " >= " + str(percent)
        percent_layer = arcpy.management.MakeFeatureLayer(raw_cell_counts, "PercentLayer", query).getOutput(0)

        # Dissolve everything that meets the threshold into one polygon
        if first:
            out_Dissolve = out_fc
        else:
            out_Dissolve = temp_out_dissolve_fc
        arcpy.management.Dissolve(percent_layer, out_Dissolve, fields_to_preserve)

        percent_field = "Percent"
        arcpy.management.AddField(out_Dissolve, percent_field, "DOUBLE")
        arcpy.management.CalculateField(out_Dissolve, percent_field, str(percent))

        if not first:
            # If this wasn't the first percent output, append it to the master output fc
            arcpy.management.Append(out_Dissolve, out_fc, "TEST")
        first = False

    # Clean up temporary output
    if arcpy.Exists(temp_out_dissolve_fc):
        arcpy.management.Delete(temp_out_dissolve_fc) 
開發者ID:Esri,項目名稱:public-transit-tools,代碼行數:42,代碼來源:CreatePercentAccessPolygon.py

示例15: exportPath

# 需要導入模塊: import arcpy [as 別名]
# 或者: from arcpy import Exists [as 別名]
def exportPath(opt, trackname):
    """
    This exports the list of segments into a shapefile, a subset of the loaded segment file, including all attributes
    """
    start_time = time.time()
    opt=getUniqueList(opt)
    qr =  '"OBJECTID" IN ' +str(tuple(opt))
    outname = (os.path.splitext(os.path.basename(trackname))[0][:9])+'_pth'
    arcpy.SelectLayerByAttribute_management('segments_lyr',"NEW_SELECTION", qr)
    try:
        if arcpy.Exists(outname):
            arcpy.Delete_management(outname)
        arcpy.FeatureClassToFeatureClass_conversion('segments_lyr', arcpy.env.workspace, outname)
        print("--- export: %s seconds ---" % (time.time() - start_time))
    except Exception:
        e = sys.exc_info()[1]
        print(e.args[0])

        # If using this code within a script tool, AddError can be used to return messages
        #   back to a script tool.  If not, AddError will have no effect.
        arcpy.AddError(e.args[0])
        arcpy.AddError(arcpy.env.workspace)
        arcpy.AddError(outname)
        #raise arcpy.ExecuteError
    except arcpy.ExecuteError:
        arcpy.AddError(arcpy.GetMessages(2))

    # Return any other type of error
    except:
        # By default any other errors will be caught here
        #
        e = sys.exc_info()[1]
        print(e.args[0])
        arcpy.AddError(e.args[0])
        arcpy.AddError(arcpy.env.workspace)
        arcpy.AddError(outname) 
開發者ID:simonscheider,項目名稱:mapmatching,代碼行數:38,代碼來源:mapmatcher.py


注:本文中的arcpy.Exists方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。