예제 #1
0
def recalculate_extent(fc):

    if arcpy.CheckProduct("ArcInfo") == "Available"                            \
    or arcpy.CheckProduct("ArcEditor") == "Available":
        arcpy.RecalculateFeatureClassExtent_management(fc)

    else:
        arcpy.CompressFileGeodatabaseData_management(fc)
        arcpy.UncompressFileGeodatabaseData_management(fc)
예제 #2
0
 def isLicensed(self):
     """Set whether tool is licensed to execute."""
     standard = arcpy.CheckProduct("ArcEditor") in ("Available",
                                                    "AlreadyInitialized")
     advanced = arcpy.CheckProduct("ArcInfo") in ("Available",
                                                  "AlreadyInitialized")
     ddd = arcpy.CheckExtension("3D") == "Available"
     spatial = arcpy.CheckExtension("Spatial") == "Available"
     return standard or advanced
예제 #3
0
def checkArcGISProduct():
    boolProductLicensAvail = False
    try:
        #Check for license availability before attempting anything else
        #Project tool available on ArcGIS Desktop Basic
        strProductCheckReturn1 = arcpy.CheckProduct("arcview")
        strProductCheckReturn2 = arcpy.CheckProduct("arceditor")
        strProductCheckReturn3 = arcpy.CheckProduct("arcinfo")      
        if ( (strProductCheckReturn1 == "Available") or (strProductCheckReturn2 == "Available") or (strProductCheckReturn3 == "Available")):
            boolProductLicensAvail = True
            print "License Available"
            #arcpy.AddMessage("License Available")
    except Exception as e:
        print "Exception caught checking license availability"
        #arcpy.AddError("Exception caught checking license availability")

    return boolProductLicensAvail
예제 #4
0
def validateLicense():
    """
    Check that the current license is using advanced.
    :return:
    """
    if not arcpy.ProductInfo() == 'ArcInfo':
        if arcpy.CheckProduct('ArcInfo') == 'available':
            arcpy.SetProduct('ArcInfo')
        else:
            raise Exception('An advanced license was not available')
예제 #5
0
 def isLicensed(self):
     """Check for Advanced license needed by Sort_management(Shape)"""
     """Allow the tool to execute, only if the ArcGIS Advanced is available."""
     try:
         license_available = ["Available", "AlreadyInitialized"]
         if not (arcpy.CheckProduct("ArcInfo") in license_available):
             raise Exception
     except Exception:
         return False
     return True
예제 #6
0
    def UKlatituderadians(self, region, river_catchment_poly):
        if arcpy.CheckProduct("ArcInfo") == "Available":

            def getlatituderadiansrivercatchment(river_catchment_poly):
                centre_point = arcpy.FeatureToPoint_management(river_catchment_poly,"out_centre_point","INSIDE")
   
                dsc = arcpy.Describe(centre_point)
                cursor = arcpy.UpdateCursor(centre_point, "", "Coordinate Systems\Geographic Coordinate Systems\World\WGS 1984.prj")
                for row in cursor:
                    shape=row.getValue(dsc.shapeFieldName)
                    geom = shape.getPart(0)
                    lat_deg = geom.Y
    
                del cursor, row
                latitude = (lat_deg * math.pi)  / 180
                arcpy.AddMessage("The latitude of the river catchment is " + str(latitude))

                return latitude
            latitude = getlatituderadiansrivercatchment(river_catchment_poly)
            
        else:
            def getlatituderadiansregion(region):

                if region == "England SW/ Wales S":
                    latitude = 0.914150067228
                elif region == "Scotland N":
                    latitude = 1.05058554677
                elif region == "Scotland E":
                    latitude = 0.971535474685
                elif region == "Scotland W":
                    latitude = 0.968875753818
                elif region == "England E & NE":
                    latitude = 0.941819912486
                elif region == "England NW/ Wales N":
                    latitude = 0.943263614828
                elif region == "Midlands":
                    latitude = 0.915926640792
                elif region == "East Anglia":
                    latitude = 0.911835053377
                elif region == "England SE/ Central S":
                    latitude = 0.891900143109
                arcpy.AddMessage("The latitude for region " + str(region) + " is " + str(latitude))
                arcpy.AddMessage("-------------------------") 

                return latitude
            latitude = getlatituderadiansregion(region)
            arcpy.AddMessage("ArcGIS for Desktop Advanced license not available")          

        return latitude
예제 #7
0
    def isLicensed(self):
        """Allow the tool to execute, only if the ArcGIS Spatial Analyst extension is available."""
        try:
            if arcpy.CheckExtension("Spatial") != "Available":
                raise Exception
        except Exception:
            return False  # tool cannot be executed
        """Allow the tool to execute, only if the ArcGIS Advanced is available."""
        try:
            license_available = ["Available", "AlreadyInitialized"]
            if not (arcpy.CheckProduct("ArcInfo") in license_available):
                raise Exception
        except Exception:
            return False  # tool cannot be executed

        return True  # tool can be executed
예제 #8
0
def checkLicenceLevel(licenceLevel):

    if licenceLevel == 'Basic':
        product = 'arcview'
    elif licenceLevel == 'Standard':
        product = 'arceditor'
    elif licenceLevel == 'Advanced':
        product = 'arcinfo'
    else:
        log.error('Licence level ' + str(licenceLevel) + ' not valid.')
        sys.exit()

    if arcpy.CheckProduct(product).strip() in [
            "Available", "AlreadyInitialized"
    ]:
        return True
    else:
        return False
예제 #9
0
                            str(re))
                else:
                    task_properties['available'] = False
                    task_properties['Error'] = str(re)
            except SyntaxError as se:
                task_properties['available'] = False
                task_properties['Python syntax error'] = str(se)

            task_info['tasks'].append(task_properties)
        sys.stdout.write(json.dumps(task_info, indent=2))
        sys.stdout.flush()
    elif sys.argv[1] == '--license':
        import arcpy
        with open(
                os.path.join(os.path.dirname(__file__), 'supportfiles',
                             'licenses.json'), 'r') as fp:
            licenses = json.load(fp)
            for product in licenses['product']:
                product['status'] = arcpy.CheckProduct(product['code'])
            for extension in licenses['extension']:
                extension['status'] = arcpy.CheckExtension(extension['code'])
        [
            licenses['extension'].remove(e) for e in licenses['extension']
            if e['status'].startswith('Unrecognized')
        ]
        sys.stdout.write(json.dumps(licenses, indent=2))
        sys.stdout.flush()
    else:
        run_task(sys.argv[1])
    sys.exit(0)
# Use of traceback to return more information about the errors should they occur.
def trace():
    import sys, traceback
    tb = sys.exc_info()[2]
    tbinfo = traceback.format_tb(tb)[0] 
    line = tbinfo.split(", ")[1]
    filename = sys.path[0] + os.sep + "1_Scale_16to_8bit_set0.py"
    synerror = traceback.format_exc().splitlines()[-1]
    return line, filename, synerror

if __name__ == '__main__':

    try:
        # Check out any necessary licenses
        if arcpy.CheckProduct("ArcInfo") == "Unavailable":
            arcpy.AddError("ArcInfo Licensing Issue")
            raise LicenseError
        if arcpy.CheckExtension("Spatial") == "Available":
            arcpy.CheckOutExtension("Spatial")
        else:
            arcpy.AddError("Spatial Analyst Licensing Issue")
            raise LicenseError

        # Script arguments
        in16Raster = arcpy.GetParameterAsText(0)# single channel 16bit SAR image(HH or HV) exported from PCI as geotif.

        # Local variable
        inRastC=os.path.join(arcpy.env.scratchWorkspace,"inRastC")
        scImage1=os.path.join(arcpy.env.scratchWorkspace,"scImage1")
        fsMedRaster=os.path.join(arcpy.env.scratchWorkspace,"fsMedRaster")
예제 #11
0
 
 # SCRIPT ARGUMENTS =================================
 inputTable = arcpy.GetParameterAsText(0)
 targetGeodatabase = arcpy.GetParameterAsText(1)
 sidcField = arcpy.GetParameterAsText(2)
 standard = arcpy.GetParameterAsText(3)
 
 # CONSTANTS ========================================
 
 # LOCALS ===========================================
 debug = True # switch off if detailed info not needed
 
 # LICENSE ==========================================
     
 # Check that we have Advanced/ArcInfo
 licenseState = arcpy.CheckProduct("ArcInfo")
 arcpy.AddMessage("ArcGIS Advanced/ArcInfo license state = " + licenseState)
 if (licenseState == "Unavailable") or (licenseState == "NotLicensed") :
     arcpy.AddError("Editing Representation Rules requires Desktop Advanced License (ArcInfo) - Tool can't continue")    
     raise Exception('License Error')
         
 # MAIN ============================================    
         
 # set command line arguments - Note: need quotes("") around command line arguments (to handle spaces)
 arguments = "\"" + str(inputTable) + "\" " + "\"" + str(targetGeodatabase) \
     + "\" " + str(sidcField) + " " + str(standard)
 
 # set command string
 # AppendMilitaryFeatures.exe <inputFeatureClass> <outputGDB> [sicField]
 currentPath = os.path.dirname(__file__)
 EXE_PATH = os.path.normpath(os.path.join(currentPath, r"../../application/"))
예제 #12
0
enableLogging = "true"  # Use logger.info("Example..."), logger.warning("Example..."), logger.error("Example...")
logFile = os.path.join(
    os.path.dirname(__file__), "Logs\LICDataWarehouseSync.log"
)  # os.path.join(os.path.dirname(__file__), "Example.log")
sendErrorEmail = "true"
emailTo = "[email protected], [email protected]"
emailUser = "******"
emailPassword = ""
emailSubject = "EDW/GIS Sync"
emailMessage = ""
enableProxy = "false"
requestProtocol = "http"  # http or https
proxyURL = ""
output = None

if arcpy.CheckProduct("ArcEditor") == "Available":
    print "License OK"
else:
    print "License not available"
    sendEmail("Quitting", "Cant get a desktop GIS license.")
    sys.exit(-99999)

# Enable data to be overwritten
arcpy.env.overwriteOutput = True

# Setup up reporting dictionary
gisReportDict = {}
gisReportCount = 0


# Start of main function
## seperate if using multipart(final spans) or single part(adjusted alignemtn) and convert to spans

desc = arcpy.Describe(INPUT_FinalSpans_Sub_Group)
shape_field = desc.ShapeFieldName

rows = arcpy.SearchCursor(INPUT_FinalSpans_Sub_Group)

Base_adj = os.path.basename(INPUT_FinalSpans_Sub_Group)
Adjusted_conversion = os.path.join(outFolder, os.path.splitext(Base_adj)[0] + "_MP_Converted_Q2.shp")



for row in rows:
    poly = row.getValue(shape_field)
    if poly.isMultipart == 1:
        if arcpy.CheckProduct("ArcInfo") == "AlreadyInitialized":
            arcpy.arcpy.AddWarning("ARC ADVANCED LICENSE DETECTED")

        else:
            arcpy.AddError("YOU NEED AN ARC ADVANCED LICENSE TO EXECUTE THIS STEP WITH AN ADJUSTED ALIGNMENT EXTRACTION")

        arcpy.SplitLine_management(INPUT_FinalSpans_Sub_Group, Adjusted_conversion)
    else:
        pass



if os.path.exists(Adjusted_conversion):
    arcpy.AddMessage("ADJUSTED ALIGNMENT DETECTED....CONVERTING ADJUSTED ALIGNMENT TO MULTI PART FEATURE(SPANS)....")
    sub_prod_ref_ADJ(Adjusted_conversion)
    sub_ref_shps_list = []
예제 #14
0
        arcpy.JoinField_management(outputFC, "Id", inputFC,
                                   arcpy.Describe(inputFC).OIDFieldName,
                                   joinFieldsParameter)

        #We don't need the new "Id_1" or "ORIG_FID" fields
        arcpy.DeleteField_management(outputFC, "Id_1")
        arcpy.DeleteField_management(outputFC, "ORIG_FID")

    except Exception as e:
        tb = sys.exc_info()[2]
        arcpy.AddError("An error occured on line %i" % tb.tb_lineno)
        print str(e)
        arcpy.AddError(str(e))

################################################################################

try:
    #Check that the appropriate license level is available to the user
    if arcpy.CheckProduct("arcinfo") != "AlreadyInitialized":
        printMessage("ERROR: The required ArcGIS for Desktop Advanced " + \
                     "license is unavailable.", 2)
    else:
        processWedges()

except Exception as e:
    tb = sys.exc_info()[2]
    arcpy.AddError("An error occured on line %i" % tb.tb_lineno)
    print str(e)
    arcpy.AddError(str(e))
예제 #15
0
# libraries
import arcpy
import os
import sys
import math

#parameters
outFileName = "TAZVertices.csv"
arcpy.env.workspace = "C:/projects/mtc/networks/MAZs/TAZ"
counties = ["Sonoma","Solano","SantaClara","SanMateo","SanFrancisco","Napa","Marin","ContraCosta","Alameda"]
simplify = False

#check for ArcInfo for simplify line tool
if simplify:
  if arcpy.CheckProduct("ArcInfo") != "Available":
    print "ArcInfo license not available"
    sys.exit("ArcInfo license not available")

#open file
f = file(outFileName,"wt")
f.write("COUNTY,TAZ,X,Y\n")

#get taz vertices for each county
for county in counties:
  
  #get taz shapefile
  print "Processing " + county
  tazs = county + "TAZ.shp"
  if simplify:
    tazsSimpleName = tazs.replace(".shp","Simple.shp")
예제 #16
0
                           MedianPoint, sr, shapeName)
        elif removalMethod == "Fixed_Median":
            FixedCenter(locationLayer, mcpFeatureClass, percentUsed,
                        MedianPoint, sr, shapeName)
        elif removalMethod == "Fixed_Mean":
            FixedCenter(locationLayer, mcpFeatureClass, percentUsed, MeanPoint,
                        sr, shapeName)
        else:
            utils.warn("Removal Method was unrecognized. Using Fixed_Mean.")
            FixedCenter(locationLayer, mcpFeatureClass, percentUsed, MeanPoint,
                        sr, shapeName)


if __name__ == "__main__":

    status = arcpy.CheckProduct("ArcInfo")
    if status != "Available" and status != "AlreadyInitialized":
        utils.die(
            "This tool requires an ArcInfo License.  License check status = " +
            status + ".  Quitting.")

    locationLayer = arcpy.GetParameterAsText(0)
    mcpFeatureClass = arcpy.GetParameterAsText(1)
    percentUsed = arcpy.GetParameterAsText(2)
    removalMethod = arcpy.GetParameterAsText(3)
    userPoint = arcpy.GetParameterAsText(4)
    spatialReference = arcpy.GetParameter(5)

    test = False
    if test:
        #locationLayer = r"C:\tmp\test.gdb\fix_ll"
            "arceditor": "ArcGIS for Desktop Standard",
            "arcinfo": "ArcGIS for Desktop Advanced",
            "engine": "Engine Runtime",
            "enginegeodb": "Engine Geodatabase Update",
            "arcserver": "Server"
           }

extensions = {"3D": "3D Analyst",
              "Schematics": "ArcGIS Schematics",
              "ArcScan": "ArcScan",
              "Business": "Business Analyst",
              "DataInteroperability": "Data Interoperability",
              "GeoStats": "Geostatistical Analyst",
              "JTX": "Workflow Manager",
              "Network": "Network Analyst",
              "Aeronautical": "Esri Aeronautical Solution",
              "Defense": "Esri Defense Solution",
              "Foundation": "Esri Production Mapping",            
              "Datareviewer": "ArcGIS Data Reviewer",
              "Nautical": "Esri Nautical Solution",
              "Nauticalb": "Esri Bathymetry",
              "Spatial": "Spatial Analyst",
              "StreetMap": "StreetMap",
              "Tracking": "Tracking"
              }

for product in products:
    print "%-44s\t%s" % (("%s (%s):" % (products[product], product)), arcpy.CheckProduct(product))

for extension in extensions:
    print "%-44s\t%s" % (("%s (%s):" % (extensions[extension], extension)), arcpy.CheckExtension(extension))
예제 #18
0
def check_product():
    return arcpy.CheckProduct("arceditor")
import arcpy
import sys
import traceback
import TestUtilities
import os

class LicenseError(Exception):
    pass

try:
        
    arcpy.ImportToolbox(TestUtilities.toolbox)
    arcpy.env.overwriteOutput = True
    
    #check product for Advanced (ArcInfo)
    productLevel = arcpy.CheckProduct("ArcInfo")
    print "CheckProduct(ArcInfo): " + productLevel

    if (productLevel == "Available"):
        import arcinfo
    elif (productLevel != "Available") and (productLevel != "AlreadyInitialized"):
        raise Exception("Advanced license is required")

    
    #Set tool param variables
    inputUTDSRoadFeatures = os.path.join(TestUtilities.inputGDB,"UTDSRoads")
    outputSplitRoadFeatures = os.path.join(TestUtilities.outputGDB,"RoadFeat")
    
    #Testing Build Elevation Mosaics - DTED input
    arcpy.AddMessage("Starting Test: Split Lines At Intersection (this test may take a while)")
    arcpy.SplitLinesAtIntersections_netprep(inputUTDSRoadFeatures,outputSplitRoadFeatures)
예제 #20
0
)  # Visulization Only; requires a valid vis.txt file in the user workspace
if visulizationOnly == 'true':
    visulizationOnly = True
else:
    visulizationOnly = False

# Body of code
try:
    # Check ArcGIS Product
    txt = 'Checking ArcGIS product level...'
    arcpy.AddMessage(txt)
    ARCproducts = ['ArcInfo', 'ArcEditor']
    ARCproductValues = ['Available', 'AlreadyInitialized']
    ARCproductFlag = False
    for ARCproduct in ARCproducts:
        if arcpy.CheckProduct(ARCproduct) in ARCproductValues:
            ARCproductFlag = True
    if ARCproductFlag == False:
        raise NoProduct
    arcpy.env.overwriteOutput = True

    # Check that all required input files are present
    txt = 'Checking for required input files and visualization flags...'
    arcpy.AddMessage(txt)
    workspaceFiles = os.listdir(userWorkspace)
    if visulizationOnly:
        txt = '\'Visulization Only\' option selected; using an existing vis.txt file; FLOWFLG assumed to be 0...'
        arcpy.AddMessage(txt)
        requiredInputFiles = ['vis.txt']
        requiredCRTFiles = []
        CASC_PCT_Flag = True  # flag - check for percent flows of either 66 or 75%