Python language
FunctionsReading/writing filesCatching exceptions
Function Definition
def function_name (arg1, arg2, …) : # arg means argument or parameter!body
# Sometimes we pass a known value for one of the arguments:def function_name (arg1, arg2=default2, arg3): # e.g., power (x, y=3)
body
Function with docsting
Function modifies a string
Pass arguments by position
Casting user’s entered value
Function traverses a string with a loop
Using datetime functions
• The age function uses the input function to get the birth year.• It then imports the datetime module• Gets the current year form the now () function.• Calculates the age, and returns it
Built in Numeric Functions
• abs(), divmod(), float(), hex(), long(), max(), min(), oct(), pow(), round()
# there are a lot more for trigonometry, etc.
• ‘none’ is a special data type for empty value– e.g., when a function does not return a value– It is used as a placeholder
Find maximum of any unknown set of arguments
• Notice that the function is called with different numbers of arguments. The * does the trick!
Defining a global variable
• Notice that calling the local variable outside of the function leads to error!
Assigning the returned value of a function to a variable
Tools in Arcpy are function!• Tools have name, which is similar to the tool’s label in ArcGIS
(without space), for example:– AddField for the Add Field tool
• The alias for a tool is not the same as its name or label.• It is a short version of it, for example:– ‘management’ is the alias for Data Management toolbox– Clip_management is the Clip tool in the Data Management
toolbox
Two ways to access a tool in ArcGIS
• All tools are available as function in Arcpy• Each tool (function) does a specific task
• To access a tool, we can:1. Call its corresponding function
arcpy.toolname_toolboxalias (arguments)
For example: call the Clip tool:>>> import arcpy>>> arcpy.env.workspace = “C:/Data”>>> arcpy.Clip_analysis (“stream.shp”, “study.shp”, “result.shp”)
Another example:>>> arcpy.env.workspace = “C:/Data/study.gdb”>>> arcpy.Buffer_analysis (“roads”, “buffer”, “100 METERS”)
Functions in ArcGIS – GetMessages()• When a tool is run in ArcGIS, messages write about
its success or failure
• To get the message, we use the following functions:
>>> arcpy.GetMessages ()>>> print arcpy.GetMessages (0) # 1st message>>> count = arcpy.GetMessageCount ()>>> print arcpy.GetMessage (count-1) # prints the last message
2. Tools are also in modules that match the toolbox alias name
arcpy.toolboxalias.toolname (arguments)• For example:
>>> import arcpy>>> arcpy.env.workspace = “C:/Data”>>> arcpy.analysis.Clip (“stream.shp”, “study.shp”, “result.shp”)
These two methods are equivalent! It depends on our preference.
Other examples>>> import arcpy>>> arcpy.env.workspace = “C:/Data”>>> infc = “streams.shp” # fc stands for feature class>>> clipfc = “study.shp”>>> outfc = “result.shp”>>> count = arcpy.GetCount_management (infc, clipfc, outfc)>>> print count # prints the count for streams>>> result = arcpy.analysis.Clip (infc, clipfc, outfc)>>> print result # prints an object# will print the path to the result shape file, i.e., : C:/Data/result.shp
Filesystem• Filesystem refers to naming, creating, moving, or referring to
files.
• Depends on the operating system.
• Pathname: String that refers to the location of the file in a directory
• Filesystem in all operating systems is a tree structure, made of a root (disk), directory, subdirectory, and its branches.
• In Windows, the \ character is used to separate the file or directory names from each other. – There is a separate root for each drive (A:\, C:\, D:\)– For example: C:\myDirectory\myfile
Paths in Python• In Python, backslash (\) is used for escape.• For example, \n and \t for line feed and tab
• Therefore, we avoid using \ in Python paths. Instead:• We use forward slash;
C:/Data/Exercise01.txt
• Or, we use double backslash (\\)C:\\Data\\Exercise01.txt
• OR, use a string litteral: #put ‘r’ before the string. r means raw stringr”C:\Data\Exercise01.txt”
• Paths are stored as string in Python!• For example, the following assigns the path to a shape file as a string for the
inputfc variable (fc is feature class in ArcGIS)>>> Inputfc = “C:/Data/lakes.shp”
Absolute path vs. relative path• Absolute path is the exact address of the file in the filesystem,
starting from the root.C:\Geoinformatics\myFile.txtA:\Courses\Python\Programming.html
• Relative path writes it with respect to another point in the file system
Python\Functions\map.txt
• We can either append a relative path to an existing absolute path.
• Or, we can implicitly reference the current working directory where a Python program may consider to be during an execution.
Current working directory - cwd
• Python knows the current directory of the file it is working on (just like you know when you work on a file that you open from a directory).
• This directory is called the ‘current working directory” or cwd for a program.
• Do the following to get the cwd of Python on your computer
Opening files in read mode
Opening a file in the write mode• We pass ‘w’ instead of ‘r’ in the 2nd argument• This will first erase data in the file before writing.• NOTE: If we want to append to the file, use ‘a’ instead of ‘w’.
Open File - example
>>> f = open ("C:/Data/mytext.txt", "w")>>> f.write ("GIS")
>>> f = open ("C:/Data/mytext.txt", "r")>>> f.read()'GIS‘
Read the number of lines in a file
• Assume the multi_line.txt file has five words written in five lines
Screen input/outputInput () is a built-in method to prompt for input; returns a string
Throwing exceptions (Error handling)• Are used to handle unusual circumstances (e.g.,
errors) encountered during the execution of the program.
• We have to realize that errors will happen, and write code to detect and handle them.
• This is done by returning a status value by a function to indicate whether a function was executed successfully or not
Raising (throwing) an exceptiontry :
# if there is no problem, do your operations here# …
except :# execute this block if there is any exception (problem)# handle possible problem here
else :# If there is no exception, execute this block# …
finally :# this always will execute. # used to manage resources (e.g., # close files).
General try/except
try: statements # Run this main action first
except name1: statements # Run if name1 is raised during the try block
except (name2, name3): statements # Run if any of these exceptions occur
except:statements # Run for all (other) exceptions raised
else: statements # Run if no exception was raised during try block
try :body # is executed first. # If successful (no error), the else block is executed, and try is finished# If exception is thrown in try, the 1st except clause is searched
except exception_type1 as var1 : # if this clause matches the error,# the error is assigned to the variable var1 after the exception type,# and the exception code below the associated type is executedexception code1 # handle the raised exception, otherwise:
except exception_type2 as var2 : # comes to here if the first except clause did not match.exception code2 # this may process if it matches
… # and so onelse : # if there is no error, come here, this is optional, and rarely used
else_bodyfinally : # optional. If it exists, it always executes
finally_body # clean up by closing files or resetting variables
Common exception errors and examples
• IOError If the file cannot be opened or read.print (“Error while reading the file”)
• ImportError If python cannot find the moduleprint (“no module found”)
• ValueError Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value
print (“non-numeric data found”)• KeyboardInterrupt Raised when the user hits the interrupt key
(normally Control-C or Delete)print (“you cancelled the operation”)
• EOFError Raised when one of the built-in functions (input() or raw_input()) hits an end-of-file condition (EOF) without reading any data
print (“end of file”)
Handle ValueError
Assign exception to variable
• Example: Define a function to get a number from a user.• Convert it into float• If it cannot be converted to float, send a message
Handle ValueError …
Exception is an object (as in OOP)• Exceptions can be raised by any function and given to a variable>>> list = [2, 4, 6]>>> x = list[2]>>> print x6
>>> x = list[4] # this raises the ‘list index out of range’ errorTraceback (most recent call last): File "<interactive input>", line 1, in <module>IndexError: list index out of range
• The error is handled by Python by writing the above message, which in this case terminates the program because there is no exception handler!
Catching when knowing the type of error
Catching multiple error types
IOError
• We use try/except for quality assurance (QA)Handle opening file issues
IOError …
IOError …
Catch all exception types
Python programs
• Up until now you have interactively used Pythonwin to communicate with the Python interpreter.
• A set of Python statements saved in a file constitutes a Python program or script.
• The program usually has a controlling function that can be called to run the program.