Python arcpy.ExecuteError() Examples

The following are 30 code examples of arcpy.ExecuteError(). 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: CreateInflowFileFromWRFHydroRunoff.py    From python-toolbox-for-rapid with Apache License 2.0 6 votes vote down vote up
def dataValidation(self, in_nc, messages):
        """Check the necessary dimensions and variables in the input netcdf data"""
        data_nc = NET.Dataset(in_nc)
        vars = data_nc.variables.keys()
        for each in self.vars_oi:
            if each not in vars:
                messages.addErrorMessage(self.errorMessages[3].format(each))
                raise arcpy.ExecuteError
            else:
                dims = data_nc.variables[each].dimensions
                if self.dims_var != dims:
                    messages.addErrorMessage(self.errorMessages[4].format(each))
                    raise arcpy.ExecuteError

        data_nc.close()

        return 
Example #2
Source File: CreateWeightTableFromWRFGeogrid.py    From python-toolbox-for-rapid with Apache License 2.0 6 votes vote down vote up
def dataValidation(self, in_nc, messages):
        """Check the necessary dimensions and variables in the input netcdf data"""
        data_nc = NET.Dataset(in_nc)
        dims = data_nc.dimensions.keys()
        globalattrs = data_nc.__dict__.keys()
        for each in self.dimensions:
            if each not in dims:
                messages.addErrorMessage(self.errorMessages[1].format(each))
                raise arcpy.ExecuteError
        for each in self.globalattributes:
            if each not in globalattrs:
                messages.addErrorMessage(self.errorMessages[2].format(each))
                raise arcpy.ExecuteError

        data_nc.close()

        return 
Example #3
Source File: mapmatcher.py    From mapmatching with MIT License 6 votes vote down vote up
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) 
Example #4
Source File: mapmatcher.py    From mapmatching with MIT License 6 votes vote down vote up
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) 
Example #5
Source File: arc_tool.py    From urbanfootprint with GNU General Public License v3.0 6 votes vote down vote up
def get_config_entity_id(username, api_key, config_entity_name, server_url):
    """Make an API query of Projects by name and return the id."""

    config_entity_id = None

    url = '{}/footprint/api/v1/project/?format=json&username={}&api_key={}&name={}'.format(
            server_url, urllib.quote(username), urllib.quote(api_key), urllib.quote(config_entity_name))

    config_entity_result = urllib2.urlopen(
        url,
        **ssl_context_kwarg
    )

    try:
        config_entity_data = json.loads(config_entity_result.read())
    except ValueError:
        raise arcpy.ExecuteError("Project lookup returned invalid response.")

    if config_entity_data and 'objects' in config_entity_data:
        if len(config_entity_data['objects']):
            config_entity_id = config_entity_data['objects'][0]['id']

    return config_entity_id 
Example #6
Source File: arc_tool.py    From urbanfootprint with GNU General Public License v3.0 6 votes vote down vote up
def login(email, password, server_url):
    """Authenticate the user."""

    api_key = None
    username = None

    try:
        login_result = urllib2.urlopen(
            '{}/footprint/login/'.format(server_url),
            data=urllib.urlencode({'email': email, 'password': password, 'output': 'json'}),
            **ssl_context_kwarg
        )
    except urllib2.HTTPError, e:
        if e.code != 200:
            raise arcpy.ExecuteError("Incorrect Email/Password combination. Please try again.")
    # raise error to user if url request fails 
Example #7
Source File: CreateInflowFileFromECMWFRunoff.py    From python-toolbox-for-rapid with Apache License 2.0 5 votes vote down vote up
def dataValidation(self, in_nc, messages):
        """Check the necessary dimensions and variables in the input netcdf data"""
        data_nc = NET.Dataset(in_nc)

        dims = data_nc.dimensions.keys()
        if dims != self.dims_oi:
            messages.addErrorMessage(self.errorMessages[1])
            raise arcpy.ExecuteError

        vars = data_nc.variables.keys()
        if vars != self.vars_oi:
            messages.addErrorMessage(self.errorMessages[2])
            raise arcpy.ExecuteError

        return 
Example #8
Source File: Generate_Regional_Transactional_MLRA_FGDB.py    From geo-pit with GNU General Public License v2.0 5 votes vote down vote up
def compareDatum(fc):
    # Return True if fc datum is either WGS84 or NAD83

    try:
        # Create Spatial Reference of the input fc. It must first be converted in to string in ArcGIS10
        # otherwise .find will not work.
        fcSpatialRef = str(arcpy.CreateSpatialReference_management("#",fc,"#","#","#","#"))
        FCdatum_start = fcSpatialRef.find("DATUM") + 7
        FCdatum_stop = fcSpatialRef.find(",", FCdatum_start) - 1
        fc_datum = fcSpatialRef[FCdatum_start:FCdatum_stop]

        # Create the GCS WGS84 spatial reference and datum name using the factory code
        WGS84_sr = arcpy.SpatialReference(4326)
        WGS84_datum = WGS84_sr.datumName

        NAD83_datum = "D_North_American_1983"

        # Input datum is either WGS84 or NAD83; return true
        if fc_datum == WGS84_datum or fc_datum == NAD83_datum:
            del fcSpatialRef, FCdatum_start, FCdatum_stop,fc_datum,WGS84_sr,WGS84_datum,NAD83_datum
            return True

        # Input Datum is some other Datum; return false
        else:
            del fcSpatialRef, FCdatum_start, FCdatum_stop,fc_datum,WGS84_sr,WGS84_datum,NAD83_datum
            return False

    except arcpy.ExecuteError:
        AddMsgAndPrint(arcpy.GetMessages(2),2)
        return False

    except:
        print_exception()
        return False

## =============================================================================================================== 
Example #9
Source File: Generate_Regional_Transactional_Region_11_FGDB.py    From geo-pit with GNU General Public License v2.0 5 votes vote down vote up
def compareDatum(fc):
    # Return True if fc datum is either WGS84 or NAD83

    try:
        # Create Spatial Reference of the input fc. It must first be converted in to string in ArcGIS10
        # otherwise .find will not work.
        fcSpatialRef = str(arcpy.CreateSpatialReference_management("#",fc,"#","#","#","#"))
        FCdatum_start = fcSpatialRef.find("DATUM") + 7
        FCdatum_stop = fcSpatialRef.find(",", FCdatum_start) - 1
        fc_datum = fcSpatialRef[FCdatum_start:FCdatum_stop]

        # Create the GCS WGS84 spatial reference and datum name using the factory code
        WGS84_sr = arcpy.SpatialReference(4326)
        WGS84_datum = WGS84_sr.datumName

        NAD83_datum = "D_North_American_1983"

        # Input datum is either WGS84 or NAD83; return true
        if fc_datum == WGS84_datum or fc_datum == NAD83_datum:
            del fcSpatialRef, FCdatum_start, FCdatum_stop,fc_datum,WGS84_sr,WGS84_datum,NAD83_datum
            return True

        # Input Datum is some other Datum; return false
        else:
            del fcSpatialRef, FCdatum_start, FCdatum_stop,fc_datum,WGS84_sr,WGS84_datum,NAD83_datum
            return False

    except arcpy.ExecuteError:
        AddMsgAndPrint(arcpy.GetMessages(2),2)
        return False

    except:
        print_exception()
        return False

## =============================================================================================================== 
Example #10
Source File: dataprep.py    From utilities-solution-data-automation with Apache License 2.0 5 votes vote down vote up
def _executePostProcess(self):
        try:
            print "Running post process GP"
            for process in self.postExtractGP:
                if process["ToolType"].upper() == "MODEL":
                    arcpy.ImportToolbox(process["ToolPath"])
                    arcpy.gp.toolbox = process["ToolPath"]
                    tools = arcpy.ListTools()
                    for tool in process["Tools"]:
                        if tool in tools:
                            customCode = "arcpy." + tool + "()"
                            print eval(customCode)
                            print "Finished executing model {0}".format(tool)
                elif process["ToolType"].upper() == "SCRIPT":
                    for tool in process["Tools"]:
                        scriptPath = process["ToolPath"] + "/" + tool
                        subprocess.call([sys.executable, os.path.join(scriptPath)])
                        print "Finished executing script {0}".format(tool)
                else:
                    print "Sorry, not a valid tool"
            return True
        except arcpy.ExecuteError:
            line, filename, synerror = trace()
            raise DataPrepError({
                "function": "CopyData",
                "line": line,
                "filename":  filename,
                "synerror": synerror,
                "arcpyError": arcpy.GetMessages(2),
            })
        except:
            line, filename, synerror = trace()
            raise DataPrepError({
                "function": "CopyData",
                "line": line,
                "filename":  filename,
                "synerror": synerror,
            }) 
Example #11
Source File: reporttools.py    From utilities-solution-data-automation with Apache License 2.0 5 votes vote down vote up
def validate_schema_map(report_schema, reclass_map, report_date_field, report_ID_field):
    try:
        valid = True
        fieldList = arcpy.ListFields(report_schema)

        layer_fields = []
        for field in fieldList:
            layer_fields.append(field.name)

        for fld in reclass_map:
            if not fld['FieldName'] in layer_fields:
                print "%s does not exist in %s" % (fld['FieldName'], report_schema)
                valid = False
        if report_date_field == '':
            print "Warning: Report Date not set in %s" % (report_schema)
        elif not report_date_field in layer_fields:
            print "%s (Report Date Field) does not exist in %s" % (report_date_field, report_schema)
            valid = False
        if not report_ID_field in layer_fields:
            print "%s (ID Field) does not exist in %s" % (report_ID_field, report_schema)
            valid = False

        if valid == False:
            raise ReportToolsError({
                "function": "validate_schema_map",
                "line": 1454,
                "filename": 'reporttools',
                "synerror": "%s does not contain all the fields contained in the config" % report_schema
            })
    except arcpy.ExecuteError:
        line, filename, synerror = trace()
        raise ReportToolsError({
            "function": "validate_schema_map",
            "line": line,
            "filename": filename,
            "synerror": synerror,
            "arcpyError": arcpy.GetMessages(2),
        })
    except ReportToolsError, e:
        raise e 
Example #12
Source File: reporttools.py    From utilities-solution-data-automation with Apache License 2.0 5 votes vote down vote up
def _CheckCreateGDBProcess(outputWorkspace):
    try:
        # If user param is to overwrite GDB, then delete it first
        if arcpy.Exists(outputWorkspace) == True:
            arcpy.Delete_management(outputWorkspace)
            print "Deleted previous GDB {0}".format(outputWorkspace)

        # if the local gdb doesn't exist, then create it using the path and name given in the end_db string
        if arcpy.Exists(outputWorkspace) == False:
            if outputWorkspace.rfind("\\") != -1:
                lastSlash = outputWorkspace.rfind("\\")
            else:
                lastSlash = outputWorkspace.rfind("/")
            arcpy.CreateFileGDB_management(outputWorkspace[:lastSlash], outputWorkspace[lastSlash + 1:])

            print "Created geodatabase {0}".format(outputWorkspace[lastSlash + 1:])


    except arcpy.ExecuteError:
        line, filename, synerror = trace()
        raise ReportToolsError({
            "function": "_CheckCreateGDBProcess",
            "line": line,
            "filename": filename,
            "synerror": synerror,
            "arcpyError": arcpy.GetMessages(2),
        })
    except:
        line, filename, synerror = trace()
        raise ReportToolsError({
            "function": "_CheckCreateGDBProcess",
            "line": line,
            "filename": filename,
            "synerror": synerror,
        })


# ---------------------------------------------------------------------- 
Example #13
Source File: csvexport.py    From utilities-solution-data-automation with Apache License 2.0 5 votes vote down vote up
def __init__(self, CSVLocation="", layer=None, workspace = None):
        # Gets the values of where the temp feature class resides and
        # the output location of the CSV.
        try:

            self._tempWorkspace = workspace
            self._layer = layer
            self._CSVLocation = CSVLocation

        except arcpy.ExecuteError:
            line, filename, synerror = trace()
            raise ReportToolsError({
                "function": "create_report_layers_using_config",
                "line": line,
                "filename":  filename,
                "synerror": synerror,
                "arcpyError": arcpy.GetMessages(2),
            }
            )
        except:
            line, filename, synerror = trace()
            raise ReportToolsError({
                "function": "create_report_layers_using_config",
                "line": line,
                "filename":  filename,
                "synerror": synerror,
            }
            ) 
Example #14
Source File: query_agol_layer_using_ArcMap_Creds.py    From ArcREST with Apache License 2.0 5 votes vote down vote up
def main(*argv):
    """ main driver of program """
    try:
        url = str(argv[0])

        arcgisSH = ArcGISTokenSecurityHandler()
        if arcgisSH.valid == False:
            arcpy.AddError(arcgisSH.message)
            return
        fl = FeatureLayer(
            url=url,
            securityHandler=arcgisSH,
            initialize=True)

        res = fl.query(where="1=1",out_fields='*',returnGeometry=False)
        arcpy.AddMessage(res)
        arcpy.SetParameterAsText(1, str(res))
    except arcpy.ExecuteError:
        line, filename, synerror = trace()
        arcpy.AddError("error on line: %s" % line)
        arcpy.AddError("error in file name: %s" % filename)
        arcpy.AddError("with error message: %s" % synerror)
        arcpy.AddError("ArcPy Error Message: %s" % arcpy.GetMessages(2))
    except FunctionError, f_e:
        messages = f_e.args[0]
        arcpy.AddError("error in function: %s" % messages["function"])
        arcpy.AddError("error on line: %s" % messages["line"])
        arcpy.AddError("error in file name: %s" % messages["filename"])
        arcpy.AddError("with error message: %s" % messages["synerror"])
        arcpy.AddError("ArcPy Error Message: %s" % messages["arc"]) 
Example #15
Source File: CreateWeightTableFromECMWFRunoff.py    From python-toolbox-for-rapid with Apache License 2.0 5 votes vote down vote up
def dataValidation(self, in_nc, messages):
        """Check the necessary dimensions and variables in the input netcdf data"""
        data_nc = NET.Dataset(in_nc)

        dims = data_nc.dimensions.keys()
        if dims not in self.dims_oi:
            messages.addErrorMessage(self.errorMessages[0])
            raise arcpy.ExecuteError

        vars = data_nc.variables.keys()
        if vars not in self.vars_oi:
            messages.addErrorMessage(self.errorMessages[1])
            raise arcpy.ExecuteError

        return 
Example #16
Source File: deleteGroup.py    From ArcREST with Apache License 2.0 5 votes vote down vote up
def main(*argv):
    """ main driver of program """
    try:
        #   Inputs
        #
        adminUsername = argv[0]
        adminPassword = argv[1]
        siteURL = argv[2]
        groupName = argv[3]
        #   Logic
        #
        sh = arcrest.AGOLTokenSecurityHandler(adminUsername, adminPassword)
        admin = arcrest.manageorg.Administration(securityHandler=sh)
        community = admin.community
        g = community.getGroupIDs(groupNames=[groupName])
        if len(g) == 0:
            arcpy.AddWarning("No Group Exists with That Name %s" % groupName)
            arcpy.SetParameterAsText(4, False)
        elif len(g) == 1:
            groups = community.groups
            groups.deleteGroup(groupId=g[0])
            arcpy.AddWarning("%s was erased." % groupName)
            arcpy.SetParameterAsText(4, True)
        else:
            arcpy.AddError("Multiple group names found, please manually delete!")
            arcpy.SetParameterAsText(4, False)
    except arcpy.ExecuteError:
        line, filename, synerror = trace()
        arcpy.AddError("error on line: %s" % line)
        arcpy.AddError("error in file name: %s" % filename)
        arcpy.AddError("with error message: %s" % synerror)
        arcpy.AddError("ArcPy Error Message: %s" % arcpy.GetMessages(2))
    except FunctionError, f_e:
        messages = f_e.args[0]
        arcpy.AddError("error in function: %s" % messages["function"])
        arcpy.AddError("error on line: %s" % messages["line"])
        arcpy.AddError("error in file name: %s" % messages["filename"])
        arcpy.AddError("with error message: %s" % messages["synerror"])
        arcpy.AddError("ArcPy Error Message: %s" % messages["arc"]) 
Example #17
Source File: deleteItem.py    From ArcREST with Apache License 2.0 5 votes vote down vote up
def main(*argv):
    """ main driver of program """
    try:
        #   Inputs
        #
        adminUsername = argv[0]
        adminPassword = argv[1]
        siteURL = argv[2]
        username = argv[3]
        itemId = argv[4]
        folderId = argv[5]
        #   Logic
        #
        sh = arcrest.AGOLTokenSecurityHandler(adminUsername, adminPassword)
        admin = arcrest.manageorg.Administration(url=siteURL,
                                                 securityHandler=sh)
        content = admin.content
        #if isinstance(content, arcrest.manageorg._content.Content): pass
        usercontent = content.usercontent(username=username)
        if folderId is None or \
           folderId == "":
            res = usercontent.deleteItem(item_id=itemId)
        else:
            res =  usercontent.deleteItem(item_id=itemId, folder=folderId)
        arcpy.SetParameterAsText(6, str(res))
    except arcpy.ExecuteError:
        line, filename, synerror = trace()
        arcpy.AddError("error on line: %s" % line)
        arcpy.AddError("error in file name: %s" % filename)
        arcpy.AddError("with error message: %s" % synerror)
        arcpy.AddError("ArcPy Error Message: %s" % arcpy.GetMessages(2))
    except FunctionError, f_e:
        messages = f_e.args[0]
        arcpy.AddError("error in function: %s" % messages["function"])
        arcpy.AddError("error on line: %s" % messages["line"])
        arcpy.AddError("error in file name: %s" % messages["filename"])
        arcpy.AddError("with error message: %s" % messages["synerror"])
        arcpy.AddError("ArcPy Error Message: %s" % messages["arc"]) 
Example #18
Source File: deleteUser.py    From ArcREST with Apache License 2.0 5 votes vote down vote up
def main(*argv):
    """ main driver of program """
    try:
        adminUsername = argv[0]
        adminPassword = argv[1]
        siteURL = argv[2]
        deleteUser = argv[3]
        #   Logic
        #
        sh = arcrest.AGOLTokenSecurityHandler(adminUsername, adminPassword)
        admin = arcrest.manageorg.Administration(securityHandler=sh)
        community = admin.community
        user = community.user
        res = user.deleteUser(username=deleteUser)
        if res.has_key('success'):
            arcpy.SetParameterAsText(4, str(res['success']).lower() == "true")
        else:
            arcpy.SetParameterAsText(4, False)
        del sh
        del admin
        del community
        del user
        del res
    except arcpy.ExecuteError:
        line, filename, synerror = trace()
        arcpy.AddError("error on line: %s" % line)
        arcpy.AddError("error in file name: %s" % filename)
        arcpy.AddError("with error message: %s" % synerror)
        arcpy.AddError("ArcPy Error Message: %s" % arcpy.GetMessages(2))
    except FunctionError, f_e:
        messages = f_e.args[0]
        arcpy.AddError("error in function: %s" % messages["function"])
        arcpy.AddError("error on line: %s" % messages["line"])
        arcpy.AddError("error in file name: %s" % messages["filename"])
        arcpy.AddError("with error message: %s" % messages["synerror"])
        arcpy.AddError("ArcPy Error Message: %s" % messages["arc"]) 
Example #19
Source File: CreateDischargeTable.py    From python-toolbox-for-rapid with Apache License 2.0 5 votes vote down vote up
def validateNC(self, in_nc, messages):
        """Check the necessary variables and dimensions in the input netcdf data"""
        data_nc = NET.Dataset(in_nc)

        vars = data_nc.variables.keys()
        vars_upper = []
        for eachvar in vars:
            vars_upper.append(eachvar.upper())

        counter = 0
        for eachvar_oi in self.vars_oi:
            try:
                ind = vars_upper.index(eachvar_oi.upper())
                # Update the Uppercase/Lowercase of the names of vars of interests
                self.vars_oi[counter] = vars[ind]
                counter += 1
            except RuntimeError:
                messages.addErrorMessage(self.errorMessages[0].format(eachvar_oi))
                raise arcpy.ExecuteError

        dims = data_nc.variables[self.vars_oi[1]].dimensions
        dims_upper = []
        for eachdim in dims:
            dims_upper.append(eachdim.upper())

        counter = 0
        for eachdim_oi in self.dims_oi:
            try:
                ind = dims_upper.index(eachdim_oi.upper())
                # Update the Uppercase/Lowercase of the names of dims of interests
                self.dims_oi[counter] = dims[ind]
                counter += 1
            except RuntimeError:
                messages.addErrorMessage(self.errorMessages[1].format(eachdim_oi, self.vars_oi[1]))
                raise arcpy.ExecuteError

        data_nc.close()

        return 
Example #20
Source File: Generate_Regional_Transactional_MLRA_FGDB.py    From geo-pit with GNU General Public License v2.0 4 votes vote down vote up
def updateAliasNames(regionChoice,fdPath):
# Update the alias name of every feature class in the RTSD including the project record.
# i.e. alias name for MUPOLYGON = Region 11 - Mapunit Polygon

    try:

        aliasUpdate = 0
        regionNumber = str([int(s) for s in regionChoice.split() if s.isdigit()][0])

        if arcpy.Exists(os.path.join(fdPath,'FEATLINE')):
            arcpy.AlterAliasName(os.path.join(fdPath,'FEATLINE'), "RTSD MLRA" + regionNumber + " - Special Feature Lines")  #FEATLINE
            aliasUpdate += 1

        if arcpy.Exists(os.path.join(fdPath,'FEATPOINT')):
            arcpy.AlterAliasName(os.path.join(fdPath,'FEATPOINT'), "RTSD MLRA" + regionNumber + " - Special Feature Points")  #FEATPOINT
            aliasUpdate += 1

        if arcpy.Exists(os.path.join(fdPath,'MUPOLYGON')):
            arcpy.AlterAliasName(os.path.join(fdPath,'MUPOLYGON'), "RTSD MLRA" + regionNumber + " - Mapunit Polygon")  #MUPOLYGON
            aliasUpdate += 1

        if arcpy.Exists(os.path.join(fdPath,'SAPOLYGON')):
            arcpy.AlterAliasName(os.path.join(fdPath,'SAPOLYGON'), "RTSD MLRA" + regionNumber + " - Survey Area Polygon")  #SAPOLYGON
            aliasUpdate += 1

        if arcpy.Exists(os.path.join(fdPath,'MULINE')):
            arcpy.AlterAliasName(os.path.join(fdPath,'MULINE'), "RTSD MLRA" + regionNumber + " - Mapunit Line")  #MULINE
            aliasUpdate += 1

        if arcpy.Exists(os.path.join(fdPath,'MUPOINT')):
            arcpy.AlterAliasName(os.path.join(fdPath,'MUPOINT'), "RTSD MLRA" + regionNumber + " - Mapunit Point")  #MUPOINT
            aliasUpdate += 1

        if arcpy.Exists(os.path.join(FGDBpath + os.sep + 'ProjectRecord' + os.sep + 'Project_Record')):
            arcpy.AlterAliasName(os.path.join(FGDBpath + os.sep + 'ProjectRecord' + os.sep + 'Project_Record'), "RTSD MLRA" + regionNumber + " - Project Record")  #Project_Record
            aliasUpdate += 1

        if aliasUpdate == 7:
            return True
        else:
            return False

    except arcpy.ExecuteError:
        AddMsgAndPrint(arcpy.GetMessages(2),2)
        return False

    except:
        print_exception()
        return False

## =============================================================================================================== 
Example #21
Source File: deleteUserContent.py    From ArcREST with Apache License 2.0 4 votes vote down vote up
def main(*argv):
    """ main driver of program """
    try:
        #   Inputs
        #
        adminUsername = argv[0]
        adminPassword = argv[1]
        siteURL = argv[2]
        username = argv[3]
        subFolders = argv[4].lower() == "true"
        #   Logic
        #
        sh = arcrest.AGOLTokenSecurityHandler(adminUsername, adminPassword)
        admin = arcrest.manageorg.Administration(url=siteURL,
                                                 securityHandler=sh)
        content = admin.content
        if isinstance(content, arcrest.manageorg._content.Content):pass
        usercontent = content.usercontent(username=username)
        res = usercontent.listUserContent(username=adminUsername)
        #   Delete Root Items
        #
        eItems = ""
        itemsToErase = ",".join([item['id'] for item in res['items']])
        usercontent.deleteItems(items=itemsToErase)
        #  Walk Each Folder and erase items if subfolder == True
        #
        if subFolders:
            for folder in res['folders']:
                c = usercontent.listUserContent(username=username, folderId=folder['id'])
                itemsToErase = ",".join([item['id'] for item in c['items']])
                if len(itemsToErase.split(',')) > 0:
                    usercontent.deleteItems(items=itemsToErase)
                del c
                usercontent.deleteFolder(folderId=folder['id'])
                del folder

        arcpy.AddMessage("User %s content has been deleted." % username)
        arcpy.SetParameterAsText(4, True)
    except arcpy.ExecuteError:
        line, filename, synerror = trace()
        arcpy.AddError("error on line: %s" % line)
        arcpy.AddError("error in file name: %s" % filename)
        arcpy.AddError("with error message: %s" % synerror)
        arcpy.AddError("ArcPy Error Message: %s" % arcpy.GetMessages(2))
    except FunctionError, f_e:
        messages = f_e.args[0]
        arcpy.AddError("error in function: %s" % messages["function"])
        arcpy.AddError("error on line: %s" % messages["line"])
        arcpy.AddError("error in file name: %s" % messages["filename"])
        arcpy.AddError("with error message: %s" % messages["synerror"])
        arcpy.AddError("ArcPy Error Message: %s" % messages["arc"]) 
Example #22
Source File: Generate_Regional_Transactional_MLRA_FGDB_old.py    From geo-pit with GNU General Public License v2.0 4 votes vote down vote up
def compareDatum(fc):
    # Return True if fc datum is either WGS84 or NAD83

    try:
        # Create Spatial Reference of the input fc. It must first be converted in to string in ArcGIS10
        # otherwise .find will not work.
        fcSpatialRef = str(arcpy.CreateSpatialReference_management("#",fc,"#","#","#","#"))
        FCdatum_start = fcSpatialRef.find("DATUM") + 7
        FCdatum_stop = fcSpatialRef.find(",", FCdatum_start) - 1
        fc_datum = fcSpatialRef[FCdatum_start:FCdatum_stop]

        # Create the GCS WGS84 spatial reference and datum name using the factory code
        WGS84_sr = arcpy.SpatialReference(4326)
        WGS84_datum = WGS84_sr.datumName

        NAD83_datum = "D_North_American_1983"

        # Input datum is either WGS84 or NAD83; return true
        if fc_datum == WGS84_datum or fc_datum == NAD83_datum:
            del fcSpatialRef
            del FCdatum_start
            del FCdatum_stop
            del fc_datum
            del WGS84_sr
            del WGS84_datum
            del NAD83_datum

            return True

        # Input Datum is some other Datum; return false
        else:
            del fcSpatialRef
            del FCdatum_start
            del FCdatum_stop
            del fc_datum
            del WGS84_sr
            del WGS84_datum
            del NAD83_datum

            return False

    except arcpy.ExecuteError:
        AddMsgAndPrint(arcpy.GetMessages(2),2)
        return False

    except:
        print_exception()
        return False

## =============================================================================================================== 
Example #23
Source File: Generate_Regional_Transactional_Region_11_FGDB_old.py    From geo-pit with GNU General Public License v2.0 4 votes vote down vote up
def updateAliasNames(regionChoice,fdPath):
# Update the alias name of every feature class in the RTSD including the project record.
# i.e. alias name for MUPOLYGON = Region 10 - Mapunit Polygon

    try:

        aliasUpdate = 0
        regionNumber = str([int(s) for s in regionChoice.split() if s.isdigit()][0])

        if arcpy.Exists(os.path.join(fdPath,'FEATLINE')):
            arcpy.AlterAliasName(os.path.join(fdPath,'FEATLINE'), "RTSD R" + regionNumber + " - Special Feature Lines")  #FEATLINE
            aliasUpdate += 1

        if arcpy.Exists(os.path.join(fdPath,'FEATPOINT')):
            arcpy.AlterAliasName(os.path.join(fdPath,'FEATPOINT'), "RTSD R" + regionNumber + " - Special Feature Points")  #FEATPOINT
            aliasUpdate += 1

        if arcpy.Exists(os.path.join(fdPath,'MUPOLYGON')):
            arcpy.AlterAliasName(os.path.join(fdPath,'MUPOLYGON'), "RTSD R" + regionNumber + " - Mapunit Polygon")  #MUPOLYGON
            aliasUpdate += 1

        if arcpy.Exists(os.path.join(fdPath,'SAPOLYGON')):
            arcpy.AlterAliasName(os.path.join(fdPath,'SAPOLYGON'), "RTSD R" + regionNumber + " - Survey Area Polygon")  #SAPOLYGON
            aliasUpdate += 1

        if arcpy.Exists(os.path.join(fdPath,'MULINE')):
            arcpy.AlterAliasName(os.path.join(fdPath,'MULINE'), "RTSD R" + regionNumber + " - Mapunit Line")  #MULINE
            aliasUpdate += 1

        if arcpy.Exists(os.path.join(fdPath,'MUPOINT')):
            arcpy.AlterAliasName(os.path.join(fdPath,'MUPOINT'), "RTSD R" + regionNumber + " - Mapunit Point")  #MUPOINT
            aliasUpdate += 1

        if arcpy.Exists(os.path.join(FGDBpath + os.sep + 'ProjectRecord' + os.sep + 'Project_Record')):
            arcpy.AlterAliasName(os.path.join(FGDBpath + os.sep + 'ProjectRecord' + os.sep + 'Project_Record'), "RTSD R" + regionNumber + " - Project Record")  #Project_Record
            aliasUpdate += 1

        if aliasUpdate == 7:
            return True
        else:
            return False

    except arcpy.ExecuteError:
        AddMsgAndPrint(arcpy.GetMessages(2),2)
        return False

    except:
        print_exception()
        return False

## ====================================== Main Body ===========================================================
# Import modules 
Example #24
Source File: Generate_Regional_Transactional_Region_11_FGDB_old.py    From geo-pit with GNU General Public License v2.0 4 votes vote down vote up
def compareDatum(fc):
    # Return True if fc datum is either WGS84 or NAD83

    try:
        # Create Spatial Reference of the input fc. It must first be converted in to string in ArcGIS10
        # otherwise .find will not work.
        fcSpatialRef = str(arcpy.CreateSpatialReference_management("#",fc,"#","#","#","#"))
        FCdatum_start = fcSpatialRef.find("DATUM") + 7
        FCdatum_stop = fcSpatialRef.find(",", FCdatum_start) - 1
        fc_datum = fcSpatialRef[FCdatum_start:FCdatum_stop]

        # Create the GCS WGS84 spatial reference and datum name using the factory code
        WGS84_sr = arcpy.SpatialReference(4326)
        WGS84_datum = WGS84_sr.datumName

        NAD83_datum = "D_North_American_1983"

        # Input datum is either WGS84 or NAD83; return true
        if fc_datum == WGS84_datum or fc_datum == NAD83_datum:
            del fcSpatialRef
            del FCdatum_start
            del FCdatum_stop
            del fc_datum
            del WGS84_sr
            del WGS84_datum
            del NAD83_datum

            return True

        # Input Datum is some other Datum; return false
        else:
            del fcSpatialRef
            del FCdatum_start
            del FCdatum_stop
            del fc_datum
            del WGS84_sr
            del WGS84_datum
            del NAD83_datum

            return False

    except arcpy.ExecuteError:
        AddMsgAndPrint(arcpy.GetMessages(2),2)
        return False

    except:
        print_exception()
        return False

## =============================================================================================================== 
Example #25
Source File: Generate_Regional_Transactional_Region_11_FGDB.py    From geo-pit with GNU General Public License v2.0 4 votes vote down vote up
def updateAliasNames(regionChoice,fdPath):
# Update the alias name of every feature class in the RTSD including the project record.
# i.e. alias name for MUPOLYGON = Region 10 - Mapunit Polygon

    try:

        aliasUpdate = 0
        regionNumber = str([int(s) for s in regionChoice.split() if s.isdigit()][0])

        if arcpy.Exists(os.path.join(fdPath,'FEATLINE')):
            arcpy.AlterAliasName(os.path.join(fdPath,'FEATLINE'), "RTSD R" + regionNumber + " - Special Feature Lines")  #FEATLINE
            aliasUpdate += 1

        if arcpy.Exists(os.path.join(fdPath,'FEATPOINT')):
            arcpy.AlterAliasName(os.path.join(fdPath,'FEATPOINT'), "RTSD R" + regionNumber + " - Special Feature Points")  #FEATPOINT
            aliasUpdate += 1

        if arcpy.Exists(os.path.join(fdPath,'MUPOLYGON')):
            arcpy.AlterAliasName(os.path.join(fdPath,'MUPOLYGON'), "RTSD R" + regionNumber + " - Mapunit Polygon")  #MUPOLYGON
            aliasUpdate += 1

        if arcpy.Exists(os.path.join(fdPath,'SAPOLYGON')):
            arcpy.AlterAliasName(os.path.join(fdPath,'SAPOLYGON'), "RTSD R" + regionNumber + " - Survey Area Polygon")  #SAPOLYGON
            aliasUpdate += 1

        if arcpy.Exists(os.path.join(fdPath,'MULINE')):
            arcpy.AlterAliasName(os.path.join(fdPath,'MULINE'), "RTSD R" + regionNumber + " - Mapunit Line")  #MULINE
            aliasUpdate += 1

        if arcpy.Exists(os.path.join(fdPath,'MUPOINT')):
            arcpy.AlterAliasName(os.path.join(fdPath,'MUPOINT'), "RTSD R" + regionNumber + " - Mapunit Point")  #MUPOINT
            aliasUpdate += 1

        if arcpy.Exists(os.path.join(FGDBpath + os.sep + 'ProjectRecord' + os.sep + 'Project_Record')):
            arcpy.AlterAliasName(os.path.join(FGDBpath + os.sep + 'ProjectRecord' + os.sep + 'Project_Record'), "RTSD R" + regionNumber + " - Project Record")  #Project_Record
            aliasUpdate += 1

        if aliasUpdate == 7:
            return True
        else:
            return False

    except arcpy.ExecuteError:
        AddMsgAndPrint(arcpy.GetMessages(2),2)
        return False

    except:
        print_exception()
        return False

## =============================================================================================================== 
Example #26
Source File: install_arcrest.py    From ArcREST with Apache License 2.0 4 votes vote down vote up
def main():
    arcrestZip = 'arcrest.zip'
    arcrestHelperZip = 'arcresthelper.zip'

    get_latest = arcpy.GetParameter(0)
    installInBoth = arcpy.GetParameter(1)
    base_folder = os.path.dirname(__file__)
    #arcpy.AddMessage("%s: " % base_folder)
    base_folder = os.path.dirname(base_folder)
    #arcpy.AddMessage("%s: " % base_folder)
    base_folder = os.path.dirname(base_folder)
    #arcpy.AddMessage("%s: " % base_folder)
    base_file = os.path.splitext(os.path.basename(__file__))[0]

    if get_latest:
        arcrest_zip, arcresthelper_zip = download_arcrest()
    else:
        commondata = os.path.join(base_folder, "commondata")
        if os.path.isdir(os.path.join(commondata, base_file)):
            arcrest_zip = os.path.join(commondata,base_file, arcrestZip)
            arcresthelper_zip = os.path.join(commondata, base_file, arcrestHelperZip)
        elif os.path.isdir(os.path.join(commondata, "userdata")):
            arcrest_zip = os.path.join(commondata, "userdata", arcrestZip)
            arcresthelper_zip = os.path.join(commondata,  "userdata", arcrestHelperZip)

    site_package = None
    site_package64 = None
    defPath =  os.path.dirname(os.__file__)
    if ('ArcGIS' in defPath):
        if ('x64' in defPath):
            site_package = os.path.join(defPath.replace('x64',''), 'site-packages')
            site_package64 = os.path.join(defPath, 'site-packages')
        else:
            site_package = os.path.join(defPath, 'site-packages')
            site_package64 = os.path.join(defPath.replace('ArcGIS','ArcGISx64'), 'site-packages')
    else:
        site_package = os.path.join(defPath,'site-packages')
##    for p in sys.path:
##        if p.lower().find("site-packages") > -1:
##            site_package = p
##            break
##        del p
    if site_package is None:
        raise arcpy.ExecuteError("Could not find the site-package folder")
    installPackages(arcrest_zip,arcresthelper_zip, site_package)

    if site_package64 is not None and installInBoth == True:
        arcpy.AddMessage(" ")
        arcpy.AddMessage("-----------------------------------------------")
        arcpy.AddMessage(" ")
        installPackages(arcrest_zip,arcresthelper_zip, site_package64)
    arcpy.AddMessage(" ")
    arcpy.AddMessage("... Process Complete ...".format(site_package)) 
Example #27
Source File: dataprep.py    From utilities-solution-data-automation with Apache License 2.0 4 votes vote down vote up
def CopyData(self):
        try:
            print "************ BEGIN Data Copy****************"
            # Read the config values and store in local variables then start extraction
            # It all depends on if it can create a GDB, if not, all other processes are bypassed.
            for database in self.databases:
                self.overWrite = None
                self.databases = None
                self.start_db =  None
                self.end_db = None
                self.datasetsToInclude = None       
                self.standaloneFeatures = None
                self.postExtractGP = None
                retVal = True
                             
                if "GDBPath" in database and "SDEPath" in database:
                    
                    #workspaceProp = arcpy.Describe(database["GDBPath"])
                    if (database["GDBPath"].lower()).find(".sde") == -1:
                    #if (workspaceProp.workspaceType == "LocalDatabase"):
                        self.start_db = database["SDEPath"]
                        self.end_db = database["GDBPath"]
                        self.overWrite = database["Overwrite"]
                        if self._CheckCreateGDBProcess():
                            if "DataSets" in database:
                                if database["DataSets"]:
                                    self.datasetsToInclude = database["DataSets"]
                                    retVal = self._CopyDatasetsProcess()
                            if "FeatureClasses" in database:
                                if database["FeatureClasses"]:
                                    self.standaloneFeatures = database["FeatureClasses"]
                                    retVal = self._CopyDataTypeProcess(type="FeatureClasses") 
                            if "Tables" in database:
                                if database["Tables"]:
                                    self.standaloneFeatures = database["Tables"]
                                    retVal = self._CopyDataTypeProcess(type="Tables")  
                    else:
                        print "The output geodatabase must be a file geodatabase" 
                        retVal = False  
                if "PostProcesses" in database:
                    if database["PostProcesses"]:
                        self.postExtractGP = database["PostProcesses"]
                        retVal = self._executePostProcess()                                          
            print "************ END Data Copy ****************"
            return retVal
        except arcpy.ExecuteError:
            line, filename, synerror = trace()
            raise DataPrepError({
                "function": "CopyData",
                "line": line,
                "filename":  filename,
                "synerror": synerror,
                "arcpyError": arcpy.GetMessages(2),
            })
        except (DataPrepError),e:
            raise e 
Example #28
Source File: createGroup.py    From ArcREST with Apache License 2.0 4 votes vote down vote up
def main(*argv):
    """ main driver of program """
    try:
        #   Inputs
        #
        adminUsername = argv[0]
        adminPassword = argv[1]
        siteURL = argv[2]
        groupTitle = argv[3]
        groupTags = argv[4]
        description = argv[5]
        access = argv[6]

        #   Logic
        #
        #   Connect to the site
        #
        sh = arcrest.AGOLTokenSecurityHandler(adminUsername, adminPassword)
        admin = arcrest.manageorg.Administration(url=siteURL,
                                                securityHandler=sh,
                                                initialize=True)
        community = admin.community
        #   Create Group
        #
        res = community.createGroup(title=groupTitle,
                                    tags=groupTags,
                                    description=description,
                                    snippet="",
                                    phone="",
                                    access=access,
                                    sortField="title",
                                    sortOrder="asc",
                                    isViewOnly=False,
                                    isInvitationOnly=False,
                                    thumbnail=None)
        arcpy.SetParameterAsText(7, str(res))
    except arcpy.ExecuteError:
        line, filename, synerror = trace()
        arcpy.AddError("error on line: %s" % line)
        arcpy.AddError("error in file name: %s" % filename)
        arcpy.AddError("with error message: %s" % synerror)
        arcpy.AddError("ArcPy Error Message: %s" % arcpy.GetMessages(2))
    except FunctionError, f_e:
        messages = f_e.args[0]
        arcpy.AddError("error in function: %s" % messages["function"])
        arcpy.AddError("error on line: %s" % messages["line"])
        arcpy.AddError("error in file name: %s" % messages["filename"])
        arcpy.AddError("with error message: %s" % messages["synerror"])
        arcpy.AddError("ArcPy Error Message: %s" % messages["arc"]) 
Example #29
Source File: reporttools.py    From utilities-solution-data-automation with Apache License 2.0 4 votes vote down vote up
def classified_pivot(classified_layer, classified_layer_field_name, reporting_areas_ID_field, count_field,
                     summary_fields=''):
    _tempWorkspace = None
    _freq = None
    _pivot = None

    try:
        _tempWorkspace = env.scratchGDB

        _freq = os.path.join(_tempWorkspace, Common.random_string_generator())
        _pivot = os.path.join(_tempWorkspace, Common.random_string_generator())

        if not count_field in summary_fields and count_field != 'FREQUENCY':
            summary_fields = count_field if summary_fields == '' else summary_fields + ";" + count_field

        arcpy.Frequency_analysis(in_table=classified_layer, out_table=_freq,
                                 frequency_fields=reporting_areas_ID_field + ';' + classified_layer_field_name,
                                 summary_fields=summary_fields)

        arcpy.PivotTable_management(_freq, reporting_areas_ID_field, classified_layer_field_name, count_field, _pivot)
        deleteFC([_freq])
        return _pivot
    except arcpy.ExecuteError:
        line, filename, synerror = trace()
        raise ReportToolsError({
            "function": "classified_pivot",
            "line": line,
            "filename": filename,
            "synerror": synerror,
            "arcpyError": arcpy.GetMessages(2),
        }
        )
    except:
        line, filename, synerror = trace()
        raise ReportToolsError({
            "function": "classified_pivot",
            "line": line,
            "filename": filename,
            "synerror": synerror,
        }
        )
    finally:
        _tempWorkspace = None
        _freq = None

        del _tempWorkspace
        del _freq

        gc.collect()


# ---------------------------------------------------------------------- 
Example #30
Source File: csvexport.py    From utilities-solution-data-automation with Apache License 2.0 4 votes vote down vote up
def WriteCSV(self):
        # This function writes the CSV. It writes the header then the rows. This script omits the SHAPE fields.
        try:
            env.workspace = self._tempWorkspace

            #fc = arcpy.ListFeatureClasses(self._layers)
            # for fcs in self._layer:
            fcs = self._layer
            if arcpy.Exists(fcs):
                with open(self._CSVLocation, 'wb') as outFile:
                    print "%s create" % self._CSVLocation
                    linewriter = csv.writer(outFile, delimiter = ',')

                    fcdescribe = arcpy.Describe(fcs)
                    flds = fcdescribe.Fields

                    # skip shape fields and derivatives
                    attrs = ("areaFieldName", "lengthFieldName", "shapeFieldName")
                    resFields = [getattr(fcdescribe, attr) for attr in attrs
                                    if hasattr(fcdescribe, attr)]

                    header,fldLst = zip(*((fld.AliasName, fld.name) for fld in flds
                                            if fld.name not in resFields))

                    linewriter.writerow([h.encode('utf8') if isinstance(h, unicode) else h for h in header])
                    linewriter.writerows([[r.encode('utf8') if isinstance(r, unicode) else r for r in row]
                                            for row in arcpy.da.SearchCursor(fcs, fldLst)])

                print "CSV file complete"
            return True
        except arcpy.ExecuteError:
            line, filename, synerror = trace()
            raise ReportToolsError({
                "function": "create_report_layers_using_config",
                "line": line,
                "filename":  filename,
                "synerror": synerror,
                "arcpyError": arcpy.GetMessages(2),
            }
            )
        except:
            line, filename, synerror = trace()
            raise ReportToolsError({
                "function": "create_report_layers_using_config",
                "line": line,
                "filename":  filename,
                "synerror": synerror,
            }
            )