• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3455
  • Last Modified:

Help with Python Script Syntax / Clean up ( ESRI ArcMap - Raster Calculator)

Hello,
I am trying to create a python script to automate some functions in ESRI ArcMap. (I previously recieved assistance with a more complicated, but similar script http://www.experts-exchange.com/Q_23068228.html).

I am trying to use a module in ArcGis Called "Int_sa". A sample scripting command from ESRI:
____________________
# Import system modules
import arcgisscripting

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

try:
    # Set the input raster dataset
    inRaster = "C:/data/ras_1"

    # Set the output raster name
    outRaster = "C:/data/final_1"

    # Check out ArcGIS Spatial Analyst extension license
    gp.CheckOutExtension("Spatial")

    # Process: Int
    gp.Int_sa(inRaster, outRaster)

except:
    # If an error occurred while running a tool, then print the messages.
    print gp.GetMessages()
___________________

The script I created (by hacking up another working script), below, tries to make this to run for more than one iteration. For clarification, 'f' is a text file with the locations of 'dem.'

I ran it from the command line as such:
C:\Python24\python "C:\dem.py" "C:\dem.txt"

I get the following error message:
Traceback (most recent call last):
  File "C\dem.py", line 38, in ?
    gp.Int_sa(inRaster, outRaster)
RuntimeError: error in executing tool

My log went to 'legit/n'
If I uncomment try and except, I get not errors and no output.
What does try and except do? And am I using the log feature correctly?

Please advise & I appreciate annotated code,
Thank you kindly,
MJ

P.S.
Someone who got the same error as me for a different process was told on an ESRI forum to:

put the processes within a try/except block with appropriate
gp.addmessage("error here at step .... " + gp.getmessages())
lines throughout to see further details of errors

But I don't really know what this is telling me to do and there was no follow up on the post.
# Multi_Output_Map_Algebra_sample.py
# Description: 
#   Runs an expression built with the Map Algebra language.
# Requirements: None
# Author: ESRI
# Date: Sept 6, 2005
# Import system modules
import sys, arcgisscripting, os
#import sys
 
def log(s):
      f = open("C:/DEM_ERROR.txt","w")
      f.write(s)
      f.close()
 
# Create the Geoprocessor object
gp = arcgisscripting.create()
inRaster = open(sys.argv[1],'r')
log("1/n")
count = 1
tmpdir = 'c:\\temp\\'
 
##try:
for dem in inRaster:
			
	# Set local variables
	outRaster = os.path.join(tmpdir, 'dem', str(count))
	log("outRaster")
	inExpression = "Int_sa(" + dem.strip() + "+ 0.5), outRaster"
	log("inExpression")
	print inExpression
	log("4/n")
	# Check out Spatial Analyst extension license
	gp.CheckOutExtension("Spatial")
	log("legit/n")
 
	# Process: MapAlgebra
	gp.Int_sa(inRaster, outRaster)
	log("5/n")
	count = count + 1
	log("6/n")
	f.close
		
##except:
    # If an error occurred while running a tool, then print the messages.
	print gp.GetMessages()

Open in new window

0
mgjust
Asked:
mgjust
  • 3
  • 2
3 Solutions
 
peprCommented:
Good point about the log() function.  You use the log() function correctly, but the function is probably slightly wrong. It overwrites the log file all the time. Change the
         f = open("C:/DEM_ERROR.txt","w")
to
         f = open("C:/DEM_ERROR.txt","a")

i.e. appending to the file instead of overwriting. Now, you will see what happened before the script stopped.

Do remove the f.close from the line 43.

If inRaster is opened text file, then you are looping through the lines, but you are also passing the open file object to the gp.Int_sa(). The gp.Int_sa() method may want to expect another type of argument. Also, your inExpression is not processed except in the log and print.

For the gp.addmessage(...) you should check the documentation. It could be something similar to your log() but using other means for collecting the messages.
0
 
mgjustAuthor Commented:
Hello,
Thanks for the reply.  I have a couple of questions.

What does the try and except 'functions' do?
Is there a way to use the template code I posted but have it run through a list of files, or look in a folder? To provide more automation to the script? In the excerpt below can the inRaster or outRaster = a list of files or a folder? Could the the glob module be used to this? Is there a generic method that might work often that I could use to replace a single input with a list or folder?

# Set the input raster dataset
    inRaster = "C:/data/ras_1"
   # Set the output raster name
    outRaster = "C:/data/final_1"


Many thanks,
MJ
0
 
peprCommented:
The try/except are not functions, but the language constructions for working with exceptions. The mechanism of exceptions is used in many other languages. The principle is that if some exception happens in the code (i.e. a kind of error like division by zero or manulally raised exception by the user/programmer), it is solved in the context of the nearest block of code below "try:". Processing of the block of code stops immediately and the nearest "except" block is searched and the block of code below the except is responsible for taking care of the exception (i.e. reporting the problem, correcting the problem in another way, etc.).

The key idea of exceptions is that if error happened it need not to be tested immediately after the action (also because programmers sometimes forgot or are lazy to do it or they do not know or do not want to make the source code unreadable...). The exception is never passed without noticing. Or it is captured somewhere in the except branch or it is reported by the Python interpreter in the form of the error report.

See what the official Tutorial says about the exceptions (http://docs.python.org/tut/node10.html).

However, the mechanism can also be misused by masking the exception using the plain form of try/except. To explain, the exception takes the form of an object that stores details about the exception inside. The exception object must be of certain base class. However, the exceptions can be of more than one classes. The recommended way of capturing the exception is to check whether some SPECIFIC exception happened. For example "RuntimeError" being one of such specific exceptions -- see http://docs.python.org/lib/module-exceptions.html for details.

If developing your own script used only by yourself, it is probably better not to use the try/except if you are not sure what you are doing. This way, the script stops when the exception happens and you will add the specific try/except only to the place where you want to solve the problem. This is the reason why I told you the last time to remove the try/except from your script.

If you still want to use the exception in the loop in your code shown above, you should put the try/except inside of the for loop. Then you can report exception inside one loop cycle and continue processing in the next loop. Otherwise, the first exception would jump out of the loop.
for dem in inRaster:
    try:                        
        # Set local variables
        outRaster = os.path.join(tmpdir, 'dem', str(count))
        log("outRaster")
        inExpression = "Int_sa(" + dem.strip() + "+ 0.5), outRaster"
        log("inExpression")
        print inExpression
        log("4/n")
        # Check out Spatial Analyst extension license
        gp.CheckOutExtension("Spatial")
        log("legit/n")
 
        # Process: MapAlgebra
        gp.Int_sa(inRaster, outRaster)
        log("5/n")
        count = count + 1
        log("6/n")
                
    except:
        # If an error occurred while running a tool, then print the messages.
        print gp.GetMessages()

Open in new window

0
 
peprCommented:
For the other part of the question, it depends what you want to do ;) I do not know what gp.Int_sa() does. Definitely, if you know that you somewhere have some important files with some regular names, you can get the list of them somehow. The glob module and glob.glob() function may be the good way to go (see http://docs.python.org/lib/module-glob.html) or os.listdir() (http://docs.python.org/lib/os-file-dir.html#l2h-2681).
0
 
mgjustAuthor Commented:
Thanks again for the python help, very thorough answers.
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now