Arc 10.0 - Pre-populate FeatureClass output box with Input Path/Filename

821
7
01-16-2012 01:44 AM
RobinPearce
New Contributor
Using ArcEditor 10.0, I am trying to resurrect the old script in Arc 9, Create Features From Textfile, which used to import textfile coords into a feature class using a script in ArcToolbox accessed from within ArcMap.

I can import the script to a new Toolbox and run it from ArcCatalog in Arc 10, but in the dialog displayed by the script, the box for the output feature class path/shapefilename is pre-populated with the path to Default.gdb in my user profile. If I clear this then go back to copy the input box, the moment I click in the input box then the outbox default contents reappear again.  I know there has been a lot of ESRI-forum traffic about location for the Default.gdb, but I am not even using a geodatabase - just going from .txt to .shp with the same root name.

What I want is simply for the featureclass dialog box to be pre-populated with the same path/filename as input/navigated to for the input text file, with the extension changed from .txt to .shp. On the odd occasion I need to change the output path/filename I can then do that in the output box hopefully. If however this Default.gdb business stops this being possible, for second-best option what is the Python code to directly create the featureclass, hardwired to input path/filename plus .shp, avoiding the dialog output box altogether?

Thanks,
Rob P
Tags (2)
0 Kudos
7 Replies
curtvprice
MVP Esteemed Contributor
You can enter whatever output name you want once it fills in the first time. If you set the current workspace to the same as the input text file, you'll at least see the path you want.  (The default workspace is Default.gdb if it hasn't been setup otherwise.)

If you want to modify what the default output path name to be the same as the input, you can do this using parameter validation in the updateParameters module:

Arc 10 help: Customizing Script Tool Behavior
0 Kudos
RobinPearce
New Contributor
You can enter whatever output name you want once it fills in the first time. If you set the current workspace to the same as the input text file, you'll at least see the path you want.  (The default workspace is Default.gdb if it hasn't been setup otherwise.)

If you want to modify what the default output path name to be the same as the input, you can do this using parameter validation in the updateParameters module:

Arc 10 help: Customizing Script Tool Behavior


Curtis,

All of my work is located in a folder called Survey_Shapes, so in order to try and set my current workspace I started my script as follows:

import arcpy
arcpy.env.workspace = "T:/Data/Survey_Shapes"

I have two parameters, InputTextFile and Output Feature Class, datatyped accordingly. When I navigate to the input file which is in Survey_Shapes folder, the output still gets pre-popped to Default.gdb in my user profile. Is there somewhere else I need to set the environment, or is this script wrong? There are so many different options related to environment it's hard to determine exactly which one is appropriate in this case,

Thanks,
Rob P
0 Kudos
curtvprice
MVP Esteemed Contributor
Rob,

There is a hierarchy to the scope of environment settings; setting environments within a script or custom tool is the lowest in the hierarchy.

Also, tool parameter validation (of which the "pop" of paths you are observing is a part) happens before your script starts, so setting arcpy.env.workspace setting in the script will not affect which path "pops" in the dialog. If you want to have the path "pop" to T:/Data/Survey_Shapes you need to either set your environment current workspace to that path in ArcCatalog, or using the environments button on the tool -- or modify the tool validation python code (in the script tool properties validation tab) to populate the same path as the input.

Rather than dink with the validation to fill in paths, I go with the flow and set the current workspace in ArcCatalog/ArcMap to where I'm working so the script tool will have the maximum flexibility. That's my recommendation.

As you suggested, you could just remove this parameter from the script and generate the output path within your python script, but this makes your script not work very well within ModelBuilder. I also don't recommend naming two objects (your example: output.txt, output.shp) the same thing -- this can cause confusion when scripting and even in your directory listing.

Hope this helps.

Curtis,

All of my work is located in a folder called Survey_Shapes, so in order to try and set my current workspace I started my script as follows:

import arcpy
arcpy.env.workspace = "T:/Data/Survey_Shapes"
0 Kudos
RobinPearce
New Contributor
Rob,

There is a hierarchy to the scope of environment settings; setting environments within a script or custom tool is the lowest in the hierarchy.

Also, tool parameter validation (of which the "pop" of paths you are observing is a part) happens before your script starts, so setting arcpy.env.workspace setting in the script will not affect which path "pops" in the dialog. If you want to have the path "pop" to T:/Data/Survey_Shapes you need to either set your environment current workspace to that path in ArcCatalog, or using the environments button on the tool -- or modify the tool validation python code (in the script tool properties validation tab) to populate the same path as the input.

Rather than dink with the validation to fill in paths, I go with the flow and set the current workspace in ArcCatalog/ArcMap to where I'm working so the script tool will have the maximum flexibility. That's my recommendation.

As you suggested, you could just remove this parameter from the script and generate the output path within your python script, but this makes your script not work very well within ModelBuilder. I also don't recommend naming two objects (your example: output.txt, output.shp) the same thing -- this can cause confusion when scripting and even in your directory listing.

Hope this helps.


Curtis,

I appreciate your advice on environment settings, but I cannot really use these in practice in my case, because I am constantly in and out of new map documents every few minutes, testing some data shapes, then starting a brand new map doc, etc., at which point I seem to lose the previous settings.

Trust me that at this point my best practical option seems to be get the Python script dialog working if it is possible. The following snippet is from my ToolValidator:

  def updateParameters(self):
    """Modify the values and properties of parameters before internal
    validation is performed.  This method is called whenever a parameter
    has been changed."""
    import string
    import os
    import arcpy
    if self.params[0].value:
      inputTxtFile = str(self.params[0].value)
      str.replace(inputTxtFile,"txt","shp")
      self.params[1].value = inputTxtFile
    return

Could you please tell me why this does not replace the default setting in my output dialog box, which still resolutely shows my user profile path, unchanged.

Many thanks,

Rob
0 Kudos
AmySmith3
New Contributor
Hello!

I'm also interested in learning how to use the Tool Validator class to update the default geodatabase so that output feature class paths are updated to match the input feature class paths. I've searched through the Tool Validation help documentation, but can't seem to find clear instruction or examples of how to do this. Any guidance would be greatly appreciated.

Thanks!

Amy
0 Kudos
RobinPearce
New Contributor
To all who may find this useful:

I have managed to get the defaulting output name thing to work - sorta.  The following script is my ToolValidator class:

class ToolValidator:
  """Class for validating a tool's parameter values and controlling
  the behavior of the tool's dialog."""

  def __init__(self):
    """Setup arcpy and the list of tool parameters."""
    import arcpy
    self.params = arcpy.GetParameterInfo()

  def initializeParameters(self):
    """Refine the properties of a tool's parameters.  This method is
    called when the tool is opened."""
    return

  def updateParameters(self):
    """Modify the values and properties of parameters before internal
    validation is performed.  This method is called whenever a parmater
    has been changed."""
    import string
    import arcpy
    if self.params[0].value:
      if not self.params[1].value:
        inputTxt = str(self.params[0].value)
        outputTxt = str.replace(inputTxt,"txt","shp")
        self.params[1].value = outputTxt
          
    return

  def updateMessages(self):
    """Modify the messages created by internal validation for each tool
    parameter.  This method is called after internal validation."""
    import os
    self.params[1].clearMessage()
    if os.path.exists(str(self.params[1])):
      self.params[1].setErrorMessage("File Exists")

    return


I incorporated the above changes into a script tool's validation tab, and the main Python script for the tool contains CreateFeaturesFromTextFile.py, which is the only available code for this tool and it was written for Arc 9.1.  In the tool dialog, upon entering input textfile name, the output shapefile box gets populated with the default name for output feature class. You can change this if it isn't quite the name you want. When you click OK on the dialog, the tool either creates the output feature class (overwriting if it already exists), or fails with an error - depending on the setting of...

gp.overwriteoutput = True/False

...near the beginning of the main tool script.  Under 10.0 this setting should be:

arcpy.env.overwriteOutput = True/False

...but this means virtually rewriting the Arc 9.1 script to 10.0, which I found impossible due to my novice Python skills. In order to catch this error before commiting the tool to failure, this setting should be in the ToolValidator but I cannot find it spellt out exactly where it should be placed. I tried _init_ and updateParameters(self) functions, to no avail.

In the Resource Centre under Customizing Script Tool Behaviour, (http://help.arcgis.com/en/arcgisdesktop/10/0/help/index.html) it says checking of output datasets is an internal validation depending on the setting of overwriteOutput (which should be placed where???), and if it's False you get an error and True you just get a warning of overwrite. This is NOT true. The tool either fails as above, or a pre-existing output file of the same name gets overwritten without warning.

My mods to updateMessages(self) don't actually do anything, but illustrate something I tried. ESRI should write some detailed instructions for migrating this tool (and the rest of the Samples library) to 10.0, but as they've been deprecated, I won't hold my breath. I cannot believe we are the only company needing to import/export textfile data in this fashion - using a format devised by ESRI after all!  Perhaps some other customer has already solved this?? Under Arc 9 the tool worked brilliantly - if your output file existed you got a red warning on the dialog outbox BEFORE hitting OK.

Thank heavens for Google, otherwise I wouldn't have got this far.

Rob P
0 Kudos
RobinPearce
New Contributor
I have now completed development of the Python code for this script. To bring the CreateFeatures tool up to Arc 10.0, proceed as follows:

In the main script, change the fileseparator character line to

fileSepChar = "."

This removes having to continually input the same character, as a separate parameter, each time you run the tool. If the decimal character is a comma in your region, change to that instead. In the lines where you run getparametersastext to input outputFC, outputSR, change the digits to 1,2 respectively (as we've removed the decimal character input).

In the script tool Properties>Parameters, set the three parameter Data Types as Text File, String, and Spatial Reference respectively.

In the script tool Properties>Validation, change the script to read as follows:

class ToolValidator:
  """Class for validating a tool's parameter values and controlling
  the behavior of the tool's dialog."""

  def __init__(self):
    """Setup arcpy and the list of tool parameters."""
    import arcpy
    self.params = arcpy.GetParameterInfo()

  def initializeParameters(self):
    """Refine the properties of a tool's parameters.  This method is
    called when the tool is opened."""
    return

  def updateParameters(self):
    """Modify the values and properties of parameters before internal
    validation is performed.  This method is called whenever a parmater
    has been changed."""
    import string
    if self.params[0].value:
      if not self.params[1].value:
        inputTxt = str(self.params[0].value)
        outputTxt = str.replace(inputTxt,"txt","shp")
        self.params[1].value = outputTxt
        
    return

  def updateMessages(self):
    """Modify the messages created by internal validation for each tool
    parameter.  This method is called after internal validation."""
    import os
    if self.params[1].altered:
      self.params[1].clearMessage()

    try:
      outputTxt = str(self.params[1].value)
      open(outputTxt)
      self.params[1].setWarningMessage(outputTxt + " exists")
    except:
      self.params[1].clearMessage()

    return


Save the updated Validator script and hit Apply, then OK. You should then be able to run the script to import ESRI-format text files into shapefile Feature classes. The behaviour of the tool as described will just give a warning over output shapefile name if such exists, but you can go ahead and optionally pick Spatial Ref for the feature class, click OK, and the shape with that name will be overwritten without further ado. Alternatively, change the output name to a new file - when you click in the Spatial Ref box the output warning message will disappear.

Hopefully this will help anyone struggling to update this tool to 10.0, or in fact any of the old Samples toolset.

Many thanks to Curtis Price taking the time to try and help me earlier.

Rob P
0 Kudos