Select to view content in your preferred language

Python Noob

2693
19
11-23-2011 04:31 PM
JoshMoloney
Emerging Contributor
Greetings,

I am an amatuer when it comes to python so could someone please help with my simple questions:

1) Is the arcpy module available in ArcGIS 9.3 (I think it is 10 / python 2.6)
2) What is the python code to open a shapefile in ArcGIS 9.3 (not using arcpy module)?

Thanks,
Josh
Tags (2)
0 Kudos
19 Replies
JoshMoloney
Emerging Contributor
Doesn't matter, it is a basic tool available in any recent python package. You just use your arcgisscripting instance instead of arcpy.
http://webhelp.esri.com/arcgisdesktop/9.3/index.cfm?id=1867&pid=1865&topicname=Make_Feature_Layer_(D...


Cheers Matt, I'll try it out
0 Kudos
JoshMoloney
Emerging Contributor
No luck.. Here's some Pseudocode:


theSession = get the current ArcMap session
theSession.addlayer(layer filepath)  'add to TOC

Please note, I mentioned shapefile before, but with some additions to my script it is now a .lyr file I need to add

Does anyone have a code sample or could someone please expose the dark secret of how to add a layer to the TOC of the current session. Remember no arcpy (Using ArcGIS 9.3.1)!
0 Kudos
MathewCoyle
Honored Contributor
Are you running this as a script tool or as a separate instance?
0 Kudos
JoshMoloney
Emerging Contributor
Are you running this as a script tool or as a separate instance?


As a script tool
0 Kudos
MathewCoyle
Honored Contributor
Try posting your entire code, use code blocks,
like this
and hopefully we can get to the bottom of your problem.
0 Kudos
JoshMoloney
Emerging Contributor
Try posting your entire code, use code blocks,
like this
and hopefully we can get to the bottom of your problem.



OK. All I want to do is add SF_RENDERED to the arcmap TOC. ArcMap session is where the script is run from (from personal arcgis tollbox).


# Import system modules
import sys, string, os, arcgisscripting


# get the shapefile
from Tkinter import * 
import tkFileDialog

# Create the Geoprocessor object
gp = arcgisscripting.create()

master = Tk() 
master.withdraw() #hiding tkinter window 
  
file_path = tkFileDialog.askopenfilename(initialdir="D:\\", title="Open file", filetypes=[("Shapefile",".shp"),("All files",".*")]) 
 
if file_path.find('.shp') == -1:
   print "Not a shapefile, quiting"     
   master.quit()

 
if file_path != "": 
   print "you chose file with path:", file_path
   SF = file_path
else: 
   print "you didn't open anything!"
   sys.exit()
   
def rchop(thestring, ending): 
  if thestring.endswith(ending): 
    return thestring[:-len(ending)] 
  return thestring

#get the tolerance
toly = 0
from tkMessageBox import askokcancel           

class Quitter(Frame):                          
    def __init__(self, parent=None):
        Frame.__init__(self, parent)
        self.pack()
        widget = Button(self, text='Done', command=self.quit)
        widget.pack(expand=YES, fill=BOTH, side=BOTTOM)
    def quit(self):
        gp.addmessage('You chose ' + ent.get() + ' for the tolerance...well played!')
        toly = ent.get()
        gp.addmessage(toly)
        gp.addmessage(toly)          
                  
           
        #local variables
        SF_Copy = rchop(file_path, '.shp') + '_copy.shp'
        SF_Copier = SF_Copy + " #"
        SF_COUNT = rchop(file_path, '.shp') + '_collectevents.shp'
        SF_Integrated = rchop(file_path, '.shp') + '_integrated.shp'
        SF_Rendered = rchop(file_path, '.shp') + '_rendered'

        # Load required toolboxes...
        gp.AddToolbox("D:/ArcGIS/ArcToolbox/Toolboxes/Spatial Statistics Tools.tbx")
        gp.AddToolbox("D:/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")


        ## Process: Copy Features...
        gp.CopyFeatures_management(SF, SF_Copy, "", "0", "0", "0")
 
        gp.addmessage('Backup copy has been made')
        ## Process: Integrate...
        gp.Integrate_management(SF_Copier, toly)
        gp.addmessage('Integration completed')
        ## Process: Collect Events...
        gp.CollectEvents_stats(SF_Copy, SF_COUNT)

        gp.addmessage('Events have been collected')
        SF_COUNT = SF_COUNT.replace("/","\\")
        SF_Rendered = SF_Rendered.replace("/","\\")
        gp.addmessage('Creating ' + SF_COUNT)
        gp.addmessage('Creating ' + SF_Rendered)


        # Process: Count Rendering...
        gp.CountRenderer_stats(SF_COUNT, "ICOUNT", SF_Rendered, "5", "bright_pink" ,"")
        Frame.quit(self)
        gp.addmessage('done and dusted')
 
 #this bit was me having a crack at adding it to the TOC
 gp.MakeFeatureLayer_management(SF_Rendered, "Untitled")
 gp.RefreshActiveView()

root = Tk()
root.title("Enter the tolerance value for integrate tool")
L1 = Label(root, text="Enter the tolerance value for integrate tool (m):  ")
L1.pack( side = LEFT)

ent = Entry(root)
ent.insert(0, '20')    
#ent.pack(side=TOP, fill=X)          
ent.pack(side=LEFT)
ent.focus()                         
#ent.bind('<Return>', (lambda event: quitter()))
ent.bind(toly, (lambda event: quitter()))       
#btn = Button(root, text='Fetch', command=fetch)    
#btn.pack(side=LEFT)
Quitter(root).pack(side=RIGHT)
root.mainloop()
0 Kudos
RuthEmerick
Emerging Contributor
0 Kudos
JoshMoloney
Emerging Contributor
How about this?

shapefile = "c://temp//shapefile.shp"

That's a joke, kind of.
What exactly are you trying to do ?  What do you mean by open?  Why can't the user add a shapefile to ArcMap and then open its attribute table or what ever it wants to do there?

What's the desired process or end result?  What does the user need to do with the shapefile once its been opened?


Jahood, do you have any input? You posed several questions and I think I answered them for you.
0 Kudos
JoshMoloney
Emerging Contributor
I'm going to develop this as a tool in trusty old Arcobjects VBA...it's crazy how hard it is to do something so simple...

Thanks for your help folks
0 Kudos
JoshMoloney
Emerging Contributor
Hello good people.

Just updating this thread with VBA code / tool that I have used instead of a python script. Thanks for your help everyone...I'm going out to buy some python books at lunch time in readiness for our upgrade to ArcGIS 10!

Private Sub ICEWR_Click()
On Error GoTo ERRORR
Dim pGxDialog As IGxDialog
Set pGxDialog = New GxDialog

pGxDialog.ButtonCaption = "Add"
pGxDialog.StartingLocation = "D:\Data"
pGxDialog.Title = "Add the shapefile you wish to integrate and collect events"

pGxDialog.AllowMultiSelect = True

Dim pLFilter As IGxFile
Set pLFilter = New GxFile

Dim pGxFilter As IGxObjectFilter
Set pGxFilter = New GxFilterShapefiles

Set pGxDialog.ObjectFilter = pGxFilter

Dim pLayerFiles As IEnumGxObject
pGxDialog.DoModalOpen 0, pLayerFiles

'Dim pLayerFile As IGxObject
Dim pLayerFile As IGxDataset
Set pLayerFile = pLayerFiles.Next

'Dim pGxLayer As IGxLayer
Dim pGxLayer As IFeatureLayer
Dim pGxFeatureClass As IFeatureClass
Set pGxFeatureClass = pLayerFile.Dataset
Set pGxLayer = New FeatureLayer
Set pGxLayer.FeatureClass = pGxFeatureClass
pGxLayer.Name = pGxFeatureClass.AliasName
theshapefile = pGxLayer.Name
Dim pMxDoc As IMxDocument
Set pMxDoc = ThisDocument



pMxDoc.AddLayer pGxLayer
pMxDoc.ActiveView.Refresh
pMxDoc.UpdateContents
Dim pMap As IMap
Set pMap = pMxDoc.FocusMap

For i = 0 To pMap.LayerCount - 1
    If pMap.Layer(i).Name = theshapefile Then
    getindex = i
    End If
Next i


Dim pl2 As IDataLayer2
Set pl2 = pMxDoc.FocusMap.Layer(getindex)
Dim pdsNAME As IDatasetName
Set pdsNAME = pl2.DataSourceName
theworkarea = pdsNAME.WorkspaceName.PathName & "\"


SF_Copy = theworkarea & theshapefile & "_copy.shp"
SF_Copier = SF_Copy & " #"
SF_COUNT = theworkarea & theshapefile & "_collectevents.shp"
SF_INTEGRATED = theworkarea & theshapefile & "_integrated.shp"
SF_Rendered = theworkarea & theshapefile & "_rendered"

toly = InputBox("Enter a tolerance value for integration please", "Tolerance")
' Create the Geoprocessor object
Set gp = CreateObject("esriGeoprocessing.GPDispatch.1")

' Load required toolboxes...
gp.AddToolbox "D:/ArcGIS/ArcToolbox/Toolboxes/Spatial Statistics Tools.tbx"
gp.AddToolbox "D:/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx"

' Process: Copy Features...
gp.CopyFeatures_management theshapefile, SF_Copy, "", "0", "0", "0"
gp.Integrate_management SF_Copier, toly
gp.CollectEvents_stats SF_Copy, SF_COUNT
gp.CountRenderer_stats SF_COUNT, "ICOUNT", SF_Rendered, "5", "bright_pink", ""

Exit Sub
ERRORR:
    MsgBox "You may have already run this and forgotten to delete files created last time", vbCritical, "Error" 'will add a file check and delete to overcome this problem when i get time
End Sub
0 Kudos