Thursday, May 31, 2012

Using Tkniter in ArcToolbox

If you download this script: http://resources.arcgis.com/gallery/file/geoprocessing/details?entryID=C2594BA8-1422-2418-A048-74E477699334 from the resource center and want to call it from a toolbox, you can do the following:

  1. Open ArcCatalog
  2. Create a new toolbox (something.tbx)
  3. Create a new script
  4. Point to the file from the download
  5. Uncheck both "Show command window when executing" and "Run python script in process"
  6. Press finish
Now the GUI form will show.  

(Note, I didn't write that script, but I'm using it as an example of showing a GUI form from ArcToolbox.  If you have issues with the code, please contact the developer of the script.)

Enjoy

Friday, May 25, 2012

Python Add-Ins for 10.1

I'm really exciting for the increasing integration of python inside of ArcGIS Desktop.  If you have done any desktop development at 10 then you will be familar with the Add-In wizard.  Check out the information here.

The types allowed: (source: webhelp.esri.com)

Add-In Type
Description
Buttons
A button is the simplest form of functionality that can be used to execute
some business logic when it is clicked. A button assumes that an action or a
series of actions will be executed. Buttons may exist on toolbars and menus.
Tools
A tool is very similar to a button. However, a tool requires user interaction
with the desktop application’s display first, and then based on that interaction,
executes some business logic. The Zoom In toolZoom In in ArcMap is a good
example—it requires that you click or drag a rectangle over a map before the
 display is redrawn, showing the map contents in greater detail for the specified
 area. Tools may exist on toolbars and tool palettes.
Combo Boxes
A combo box provides a set of choices, visually seen as a drop-down box, from
which a selection can be made and acted upon. A combo box can also be
enabled to allow an end user to add a value in the combo box. The Scale combo
box Scale Drop-down List in ArcMap is a good example of a combo box. When data with a known
coordinate system is added to ArcMap, the scale combo box is enabled giving
the user a set of predefined scales from which to choose. It also allows a
user to type a new scale not in the list of options, and the display is updated
based on the value added.
Menus
A menu is a container for buttons or other menus. Menus can be exposed by
adding them to an existing toolbar (see Creating an Add-In toolbar for more
information on creating your own toolbar) or an existing menu.
Toolbars
A toolbar is a container for buttons, tools, combo boxes, tool palettes, and menus.
Toolbars can be floating or docked in desktop applications, just like any system
toolbar within the application. Toolbars can also be activated so they are visible
when a desktop application is started.
Tool Palettes
A tool palette is a container for tools. Tool palettes can only be exposed by adding
 them to an existing toolbar (see Creating an Add-In toolbar for more information
on creating your own toolbar).
Application Extensions
Application extensions can be used in different ways to provide supplemental
functionality to ArcGIS Desktop:
1. Application extensions are used to coordinate activities between other components
—such as buttons and tools—within a containing add-in. For example, an extension
 may not activate a set of tools on a toolbar unless a specific set of layers exist in the map.
2. Application extensions are usually responsible for listening and responding to various
events exposed by the host application. For example, anytime a layer is added
 or removed, an event is triggered, and the extension responds by
automatically saving the map document.

Thursday, May 24, 2012

Feature Class as JSON (ArcPy 10.1)

I just learned a really easy way to display a feature class as JSON by using featureset object and the Describe().

fc = r"c:\temp\myData.shp"
featurSet = arcpy.FeatureSet()
featureSet.load(fc)
desc = arcpy.Describe(featureSet)
print desc.pjson # so we can read it
#### desc.json also works. ####
del desc
del fc
del featureSet

Output


{
  "displayFieldName" : "",
  "geometryType" : "esriGeometryPolygon",
  "spatialReference" : {
    "wkid" : 4326,
    "latestWkid" : 4326
  },
  "fields" : [
    {
      "name" : "FID",
      "type" : "esriFieldTypeOID",
      "alias" : "FID"
    },
    {
      "name" : "Id",
      "type" : "esriFieldTypeInteger",
      "alias" : "Id"
    }
  ],
  "features" : [
    {
      "attributes" : {
        "FID" : 0,
        "Id" : 0
      },
      "geometry" : {
        "rings" : [
          [
            [
              -170.48758544651321,
              27.863404726470606
            ],
            [
              -167.28669772639196,
              27.956184080677076
            ],
            [
              -167.28669772639196,
              25.497531194206999
            ],
            [
              -170.53397512361644,
              25.327435711495355
            ],
            [
              -170.48758544651321,
              27.863404726470606
            ]
          ],
          [
            [
              -169.37423319603627,
              27.229412472726722
            ],
            [
              -169.28145384182986,
              25.961427965239068
            ],
            [
              -167.90522675443472,
              26.208839576456285
            ],
            [
              -167.93615320583692,
              27.337655052634318
            ],
            [
              -169.37423319603627,
              27.229412472726722
            ]
          ]
        ]
      }
    }
  ]
}


Enjoy

Wednesday, May 23, 2012

Python for ArcGIS 10.1

At 10.1, python developers will be using Python 2.7.  This is the last 2.x release of python before moving to the Python 3.x releases.  You can find out all about python 2.7 here.

Enjoy

Tuesday, May 22, 2012

Compressing File Geodatabases in a Folder

In a previous post, I showed how to uncompress a set of file geodatabases in a folder.  To compress a set of file geodatabases, using the CompressFileGeodatabase_management().  This script will use the List functions to list all the file geodatabases and then compress them.  When completed successfully it returns 'true' else it returns false.

import arcpy
from arcpy import env
if __name__ == '__main__':
    try:
        workspace = arcpy.GetParameterAsText(0)
        env.workspace = workspace
        fgdbs = arcpy.ListWorkspaces("*","FileGDB")
        for fgdb in fgdbs:
            arcpy.CompressFileGeodatabaseData_management(fgdb)
        env.workspace = None
        arcpy.SetParameterAsText(1,True)
    except:
        env.workspace = None
        arcpy.AddError(str(arcpy.GetMessages(2)))
        arcpy.SetParameterAsText(1,False)

Enjoy

Monday, May 21, 2012

Checking Hard Drive Space Using Python

Have you ever needed to check how much space is left on a drive, but didn't know how, well now you will.  Python ctypes and os libraries allow a developer to check the HD space pretty easily.  If you have a windows system, you can use ctypes to leverage the kernal32.dll functions, and if you have the other operating systems, python has a built in function called os.statvfs().


import ctypes
import platform
import os


class HardDriveSpaceException(Exception):
    def __init__(self, value):
        self.parameter = value
    def __str__(self):
        return repr(self.parameter)


def get_free_space(folder, format="MB"):
    """ 
        Return folder/drive free space 
    """
    fConstants = {"GB": 1073741824,
                  "MB": 1048576,
                  "KB": 1024,
                  "B": 1
                  }
    if platform.system() == 'Windows':
        free_bytes = ctypes.c_ulonglong(0)
        ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(folder), None, None, ctypes.pointer(free_bytes))
        return (int(free_bytes.value/fConstants[format.upper()]), format)
    else:
        return (int(os.statvfs(folder).f_bfree*os.statvfs(folder).f_bsize/fConstants[format.upper()]), format)
if __name__ == "__main__":
    try:
        byteformat = "mb"
        size =  get_free_space(r"c:", byteformat)
        print size
        if size[0] < 10000000000:
            raise HardDriveSpaceException("Hard drive space limit reached, there is only %s %s space left." % (size[0],size[1]))
    except HardDriveSpaceException as e:
        print e

In this example, there is a function that checks your HD space, and a custom error. The custom error is raised if the numeric value is over a specific value.

I've tested the HD space function on Win7, Win7 x64, and Window Server 2008 R2 x64.  It works.  I don't have any OS's that aren't windows based, so let me know if it works on iOS or the other that some people use.

Some maybe wondering why would I want to do something like this.  Well, if you are creating content automatically, such as PDFs or any geospatial content, you want to ensure that you have the space to save it.

Enjoy

Friday, May 18, 2012

Uncompressing Multiple File Geodatabases

Often when I receive spatial data from individuals on a DVD or CD, it is in the form of a file geodatabase and it's compressed.  If all the data is in a single file geodatabase, it is not a big problem, but when you get multiple file geodatabases, that's when I break out my python.

Here is a helpful little script that will try to uncompress all file geodatabases in a single folder.  It should be noted that if a file geodatabase is already uncompressed, it will just be ignored.


import arcpy
from arcpy import env
if __name__ == '__main__':
    try:
        workspace = arcpy.GetParameterAsText(0)
        env.workspace = workspace
        fgdbs = arcpy.ListWorkspaces("*","FileGDB")
        for fgdb in fgdbs:
            arcpy.UncompressFileGeodatabaseData_management(fgdb)
        env.workspace = None
        arcpy.SetParameterAsText(1,True)
    except:
        arcpy.AddError(str(arcpy.GetMessages(2)))
        arcpy.SetParameterAsText(1,False)
So what I have done is list all file geodatabases in a given workspace (folder), then I just use the standard UncompressFileGeodatabaseData_management().  When I'm done processing, I set my environmental workspace variable to None just to clean up some loose ends.  I could delete the object like fgdbs, but since they are self contained within the function, those variables should not persist beyond the life of the function.

Enjoy