2

In the code below just before the arcpy.AddMessage("Finished!") statement I have used a selection Query. The problem is that the newly created shapefile Testing1 in which am firing the query is unable to locate Testing1.

The reason why it was unable to locate Testing1 was that it was not present in the table of contents. But when I remove the selection query the code works fine and Testing1 is shown in the table of contents.

Why so?

Is there a life-cycle after the end of the script that allows the Testing1 shapefile to be displayed on to the table of content?

If there is how can I append that to make my selection query work?

############################################################################
## Tool name: BetterBusBuffers - Count Trips at Stops
## Created by: Melinda Morang, Esri, mmorang@esri.com
## Last updated: 4 April 2014
############################################################################

''' BetterBusBuffers - Count Trips at Stops

BetterBusBuffers provides a quantitative measure of access to public transit
in your city by counting the transit trip frequency at various locations.

The Count Trips at Stops tool creates a feature class of your GTFS stops and
counts the number of trips that visit each one during a time window as well as
the number of trips per hour and the maximum time between subsequent trips
during that time window.
'''

import arcpy
import BBB_SharedFunctions


class CustomError(Exception):
    pass


try:
    # ------ Get input parameters and set things up. -----
    try:

        # Path for output feature class of GTFS stops.
        # Must be a file geodatabase feature class, not a shapefile.
        outStops = arcpy.GetParameterAsText(0)

        # GTFS SQL dbase - must be created ahead of time.
        SQLDbase = "C:/Users/Gurminder/Desktop/sir/temp.sql" 
        #arcpy.GetParameterAsText(1)
        BBB_SharedFunctions.ConnectToSQLDatabase(SQLDbase)

        # Day and time window to analyze
        DayOfWeek = arcpy.GetParameterAsText(2)
        # Lower end of time window (HH:MM in 24-hour time)
        start_time = arcpy.GetParameterAsText(3)
        # Default start time is midnight if they leave it blank.
        if start_time == "":
            start_time = "00:00"
        # Convert to seconds
        start_sec = BBB_SharedFunctions.parse_time(start_time + ":00")
        # Upper end of time window (HH:MM in 24-hour time)
        end_time = arcpy.GetParameterAsText(4)
        # Default end time is 11:59pm if they leave it blank.
        if end_time == "":
            end_time = "23:59"
        # Convert to seconds
        end_sec = BBB_SharedFunctions.parse_time(end_time + ":00")

        # Will we calculate the max wait time? This slows down the calculation, so leave it optional.
        CalcWaitTime = arcpy.GetParameterAsText(5)

        # Does the user want to count arrivals or departures at the stops?
        DepOrArrChoice = arcpy.GetParameterAsText(6)
        if DepOrArrChoice == "Arrivals":
            DepOrArr = "arrival_time"
        elif DepOrArrChoice == "Departures":
            DepOrArr = "departure_time"

        # Figure out what version of ArcGIS they're running
        ArcVersionInfo = arcpy.GetInstallInfo("desktop")
        ArcVersion = ArcVersionInfo['Version']

    except:
        arcpy.AddError("Error getting user inputs.")
        raise


    # ----- Create a feature class of stops and add fields for transit trip counts ------
    #TODO itteration can be done here
    try:
        arcpy.AddMessage("Creating feature class of GTFS stops...")

        # Create a feature class of transit stops
        outStops, StopIDList = BBB_SharedFunctions.MakeStopsFeatureClass(outStops)

        # Add a field to the output file for number of trips, num trips / hour, and max wait time
        if ".shp" in outStops:
            # Shapefiles can't have long field names
            arcpy.management.AddField(outStops, "NumTrips", "SHORT")
            arcpy.management.AddField(outStops, "TripsPerHr", "DOUBLE")
            arcpy.management.AddField(outStops, "MaxWaitTm", "SHORT")
        else:
            arcpy.management.AddField(outStops, "NumTrips", "SHORT")
            arcpy.management.AddField(outStops, "NumTripsPerHr", "DOUBLE")
            arcpy.management.AddField(outStops, "MaxWaitTime", "SHORT")

    except:
        arcpy.AddError("Error creating feature class of GTFS stops.")
        raise


    #----- Query the GTFS data to count the trips at each stop -----
    try:
        arcpy.AddMessage("Calculating the number of transit trips available during the time window...")

        # Get a dictionary of {stop_id: [[trip_id, stop_time]]} for our time window
        stoptimedict = BBB_SharedFunctions.CountTripsAtStops(DayOfWeek, start_sec, end_sec, DepOrArr)

        # TODO run 24 times to create 24 shapefile for monday saturday sunday
        # Solution create 24 stoptimedict varibles with different start_sec and end_sec parameters     
    except:
        arcpy.AddError("Error counting arrivals or departures at stop during time window.")
        raise


    # ----- Write to output -----
    try:
        arcpy.AddMessage("Writing output data...")

        # Create an update cursor to add numtrips, trips/hr, and maxwaittime to stops
        if ArcVersion == "10.0":
            if ".shp" in outStops:
                ucursor = arcpy.UpdateCursor(outStops, "", "", "stop_id; NumTrips; TripsPerHr; MaxWaitTm")
                #TODO all shapefiles should itterate here
                for row in ucursor:
                    NumTrips, NumTripsPerHr, NumStopsInRange, MaxWaitTime = \
                            BBB_SharedFunctions.RetrieveStatsForSetOfStops(
                                [str(row.getValue("stop_id"))], stoptimedict,
                                CalcWaitTime, start_sec, end_sec)
                    row.NumTrips = NumTrips
                    row.TripsPerHr = NumTripsPerHr
                    if MaxWaitTime == None:
                        row.MaxWaitTm = -1
                    else:
                        row.MaxWaitTm = MaxWaitTime
                    ucursor.updateRow(row)
            else:
                ucursor = arcpy.UpdateCursor(outStops, "", "", "stop_id; NumTrips; NumTripsPerHr; MaxWaitTime")
                for row in ucursor:
                    NumTrips, NumTripsPerHr, NumStopsInRange, MaxWaitTime = \
                            BBB_SharedFunctions.RetrieveStatsForSetOfStops(
                                [str(row.getValue("stop_id"))], stoptimedict,
                                CalcWaitTime, start_sec, end_sec)
                    row.NumTrips = NumTrips
                    row.NumTripsPerHr = NumTripsPerHr
                    row.MaxWaitTime = MaxWaitTime
                    ucursor.updateRow(row)

        else:
            # For everything 10.1 and forward
            if ".shp" in outStops:
                ucursor = arcpy.da.UpdateCursor(outStops,
                                            ["stop_id", "NumTrips",
                                             "TripsPerHr",
                                             "MaxWaitTm"])
            else:
                ucursor = arcpy.da.UpdateCursor(outStops,
                                            ["stop_id", "NumTrips",
                                             "NumTripsPerHr",
                                             "MaxWaitTime"])
            for row in ucursor:
                NumTrips, NumTripsPerHr, NumStopsInRange, MaxWaitTime = \
                            BBB_SharedFunctions.RetrieveStatsForSetOfStops(
                                [str(row[0])], stoptimedict, CalcWaitTime,
                                start_sec, end_sec)
                row[1] = NumTrips
                row[2] = NumTripsPerHr
                if ".shp" in outStops and MaxWaitTime == None:
                    row[3] = -1
                else:
                    row[3] = MaxWaitTime
                ucursor.updateRow(row)

    except:
        arcpy.AddError("Error writing to output.")
        raise


    arcpy.SelectLayerByAttribute_management ("Testing1", "NEW_SELECTION", " NumTrips > 0 ")    
    arcpy.AddMessage("Finished!")
    arcpy.AddMessage("Your output is located at " + outStops)

except CustomError:
    arcpy.AddError("Failed to count trips at stops.")
    pass

except:
    arcpy.AddError("Failed to count trips at stops.")
    raise

arcpy.AddMessage("Checking curosr")
  • after running the script can you manually execute arcpy.SelectLayerByAttribute_management ("Testing1", "NEW_SELECTION", " NumTrips > 0 ") ? – wittich Nov 11 '15 at 10:41
  • I know but is there any way in which i can include the selection method with in the script? @wittich – Gurminder Bharani Nov 11 '15 at 10:54
  • So manually it works to execute the command? – wittich Nov 11 '15 at 11:01
  • Yes its works @wittich – Gurminder Bharani Nov 11 '15 at 11:06
  • Did the arcpy.RefreshCatalog() helped? – wittich Nov 11 '15 at 11:18
4

The problem here is that this is a script tool. "Testing1" is added to your map document because it is the output of the scripting tool and you have ArcGIS Desktop configured to add script tool output to the map.

The script itself does not add your output to the map. Because of this, when you read line 176 and try to access the "Testing1" layer, it does not exist. It will not exist until the script finishes executing and ArcGIS Desktop adds the output of the script tool to your map document. Again, this is a separate operation that happens outside your script.

In the meantime, Testing1.shp does exist (or rather outStops exists) once you reach line 81. Lines 84-92 create the fields for the feature class while the data is loaded into it by the end of the try block at line 173.

So... how to fix this....
You will have to use arcpy.mapping to get around the fact that your feature class is not added to the map until you exit the script. arcpy.mapping is pretty version dependent, so I will write a sample that fits for 10.1-10.3.1. These lines go around line 174, just before your arcpy.SelectLayerByAttribute_management statement.

mxd = arcpy.mapping.MapDocument(r"CURRENT")
#Reference to current map document. Only works if ArcGIS Desktop is open!
df = arcpy.mapping.ListDataFrames(mxd)[0]
#First dataframe in the document. Be careful if you have multiple dataframes
arcpy.RefreshCatalog() #Make sure outStops is available to create Layer
addLayer = arcpy.mapping.Layer(outStops) #This does not add the layer to the map yet
arcpy.mapping.AddLayer(df, addLayer) #This does add the layer to the map
arcpy.RefreshTOC() #Updates the TOC so that layer is now definitely available for select
arcpy.RefreshActiveView() #Updates the view of the map too

For your arcpy.SelectLayerByAttribute_management statement, change it to this to reference your new layer:
arcpy.SelectLayerByAttribute_management(addLayer, "NEW_SELECTION", "NumTrips > 0")

  • thank you for taking out your time and solving my problem – Gurminder Bharani Dec 3 '15 at 18:33
1

As far as I know there is no lifecycle or anything else. Usually this happens if the create function is not totally finished.

EDIT:

see correct answer from @blord-castillo


1st try

Maybe a refresh of the catalog just before the arcpy.SelectLayerByAttribute_management() helps:

# Refresh the Catalog window for the new directory
arcpy.RefreshCatalog(target_folder)

2nd try

Try to put the function on the end. Maybe the try: has to finish:

[...]

    #arcpy.SelectLayerByAttribute_management ("Testing1", "NEW_SELECTION", " NumTrips > 0 ")    
    arcpy.AddMessage("Finished!")
    arcpy.AddMessage("Your output is located at " + outStops)

except CustomError:
    arcpy.AddError("Failed to count trips at stops.")
    pass

except:
    arcpy.AddError("Failed to count trips at stops.")
    raise

arcpy.AddMessage("Checking curosr")

# insert it here
if arcpy.Exists(outStops):
    arcpy.SelectLayerByAttribute_management (outStops, "NEW_SELECTION", " NumTrips > 0 ") 
    arcpy.AddMessage("NumTrips > 0 is selected")
else: 
    arcpy.AddError("Coundn't find " + outStops + ".")

3rd try

Try to use with-statements as it searches and updates the cursors. Example:

with arcpy.da.UpdateCursor(fc, ['fieldA', 'fieldB']) as cursor:
    for row in cursor:
        print(row)

More information here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.