Select to view content in your preferred language

Running Python without ArcGis interface

1161
3
11-03-2011 07:48 AM
JaimeMillan
Emerging Contributor
Hi, I'm running a loop over network analysis (270x56 matrix). The loop is working much better now but I would like to know if there is a way to run a python code over ArcGis with out open the ArcMap interface.
What is more, I cannot run my code directly from the python shell and I always have to manually upload the layers that i need as inputs, load my code in the ArcGis python interface and the run it. Is it possible to upload and use layers using a python code?
Thanks in advance. Below you find a copy of my python code.
Best
J
*******************
#****************************************************************************
#****************************************************************************
#   FIND THE ROUTES AND EXPORT
#****************************************************************************
#      Description:
#           This script aims to find and save the best route from each starting
#           point x to each destination point y, over the network of roads.
#           to do this I follow these steps
#               1. Create master layer, input layers and the output base
#               2. loop over origin x and destination y:
#                   a. Create the stops
#                   b. Solve the route
#                   c. Select roads and municipalities and save them in output layers
#                   d. Clean master layers
#****************************************************************************

#*******************************************************************************
#   VERY IMPORTANT ->   REMEMBER TO THE FILES IN THE WORKING AND OUTPUT FOLDERS
#*******************************************************************************

#*******************************************************************************
# PREABULE
#*******************************************************************************

# Declare: Folder Paths
path = "C:\Users\uctpjam\AnalysisDDRoutes111020\\"
#           The path is the key local to change in order to run the same program over
#           different folders.
pathWorking = path + "ToWork\\"
pathOutput = path + "Output\\"

# Declare: Network Analysis Locals
MRoute = "MasterRoute" # I can solve over one Make a route layer
inputLyr = MRoute + "/Routes"
NetLines = "vias_unificado"
Active_Net = "Roads/vias_unificado_ND" # Active network
hrch = "USE_HIERARCHY"  # Declare Hierarchy
cost = "Length" # Cost variable#
op1 = "USE_INPUT_ORDER"
op2 = "PRESERVE_BOTH"
op3 = "NO_TIMEWINDOWS"
op4 = "ALLOW_UTURNS"
op5 = "TRUE_LINES_WITH_MEASURES"

# Declare: Program local variables
Org = "orgRoads"
Dest = "destRoads"
Stp = Org + ";" + Dest
mStop = "Stops_Master"
mpios = "wlMunicipios"
baseMpio = "routesMnpAll"
baseLine = "routesLineAll"

# Call the packages
import arcpy, os    # Argis
from arcpy import env # Import environments
env.workspace = path


# **************************************************************************************
# 1. SET UP MAIN AND MASTER LAYERS
# **************************************************************************************


# Check out any necessary licenses
arcpy.CheckOutExtension("Network")

# Process: Make Route Layer
arcpy.MakeRouteLayer_na(Active_Net, MRoute, cost, op1, op2, op3, "", op4, "",hrch, "", op5, "")

# Process: Master Stop Layer
arcpy.CreateFeatureclass_management(pathWorking,mStop,"POINT",Org)

# Process: Municipalities Output
#       Note: I'm having problems with the field names. What I'm doing is to create 2
#               copies of the "Municipios" Layer, one empty one as master layer
#               and one full as input layer.
arcpy.CreateFeatureclass_management(pathOutput,baseMpio,"POLYGON",mpios) # Master layer

# Process: Output Road Layer
arcpy.CreateFeatureclass_management(pathOutput,baseLine,"POLYLINE",NetLines) # Base

# Process: Add Field with the route name
LYR = [baseMpio, baseLine, NetLines, mpios]
for i in LYR:
    arcpy.DeleteField_management(i,"routeCode")
    arcpy.AddField_management(i,"routeCode","TEXT","#","#","#","#","NULLABLE","NON_REQUIRED","#")
# Process: Expression (core) to get the route layer
expression = "categoria(!routeCode!)"

# **************************************************************************************
# 2. FIND THE ROUTES - LOOP OVER ORIGIN/DESTINATIONS
# **************************************************************************************

for x in range(0,270):
    for y in range(0,56):
       
        # Declare Local Variables
        selectOrg ="FID=" + str(x)
        selectDest ="FID=" + str(y)
        outRuta = "Route_"+str(x)+"_"+str(y)
        rutaVar = "'" + outRuta + "'"
        vLocal = "selecOrg, selectDest, outRuta, rutaVar"

        # Process: Select Origin and Destination
        arcpy.SelectLayerByAttribute_management(Org, "NEW_SELECTION", selectOrg)
        arcpy.SelectLayerByAttribute_management(Dest, "NEW_SELECTION", selectDest)

        # Process: Append the stops to Stop Master
        arcpy.Append_management(Stp, mStop)

        # Process: Add stops
        arcpy.AddLocations_na(MRoute, "Stops", mStop, "Name Name #", "10000 Meters","","","","CLEAR")

        # Process: Define the expression to get the route code
        codeblock = """def categoria(routeCode):
            if routeCode == ' ':
                return outRuta"""
       
        try:
            # Process: Solve
            arcpy.Solve_na(MRoute, "SKIP", "TERMINATE")

            # Process: Select by location and create new layer with the municipalities
            arcpy.SelectLayerByLocation_management(mpios,"INTERSECT",inputLyr,"#","NEW_SELECTION")
            arcpy.Append_management(mpios, baseMpio)

            # Process: Select by location and create new layer with the roads
            arcpy.SelectLayerByLocation_management(NetLines,"INTERSECT",inputLyr,"#","NEW_SELECTION")
            arcpy.Append_management(NetLines, baseLine)

            # Process: Route code
            arcpy.CalculateField_management(baseMpio,"routeCode",expression,"PYTHON_9.3",codeblock)
            arcpy.CalculateField_management(baseLine,"routeCode",expression,"PYTHON_9.3",codeblock)
           
        except:
            print "Error ->  " + outRuta +" doesn't exist"

        # Process: Clear Master Layers
        arcpy.DeleteFeatures_management(mStop)
   
        del vLocal
        del codeblock
       
#****
Tags (2)
0 Kudos
3 Replies
ChrisSnyder
Honored Contributor
I almost exclusivly write and run my Python code from the PythonWin IDE. There are many Python code editors out there, but PythonWin is simple and does everything I need, so that's why I use it.

PythonWin comes with the ArcGIS install CD (you have to manually install it!), but you can also download it free from here: http://sourceforge.net/projects/pywin32/files/pywin32/Build216/

Important: Download "pywin32-216.win32-py2.6.exe" as that is Python version (v2.6) that ArcGIS v10.0 uses. DO NOT try and get fancy and upgrade to a different version - it will not work.
0 Kudos
IanJohnson
Deactivated User
Important: Download "pywin32-216.win32-py2.6.exe" as that is Python version (v2.6) that ArcGIS v10.0 uses. DO NOT try and get fancy and upgrade to a different version - it will not work.


Thanks for that little nugget of information. I had pulled down the newest version online rather than getting it from the install disc and it wasn't working well.

Ian
0 Kudos
StacyRendall1
Frequent Contributor
Data sources and feature classes are items on your hard disk (i.e. in folders or GDBs); when you load these onto a map/the screen they become feature layers.

The reason you have to use ArcMap at the moment is that your code calls feature layers. You need to use the arcpy tool Make Feature Layer (info here) on your original data set first. I.e.:
input = 'c:\\data\\data.gdb\\network'
Active_Net = 'Active_Network' # any name can go here...
arcpy.MakeFeatureLayer_management(input, Active_Net)

Your other inputs will have the same problem, so you will need to fix them all.
0 Kudos