1 / 45

Python language

Python language. Functions Reading/writing files C atching exceptions. Function Definition. d ef function_name (arg1, arg2, …) : # arg means argument or parameter! body # Sometimes we pass a known value for one of the arguments:

Download Presentation

Python language

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Python language Functions Reading/writing files Catching exceptions

  2. Function Definition deffunction_name (arg1, arg2, …) : # arg means argument or parameter! body # Sometimes we pass a known value for one of the arguments: deffunction_name (arg1, arg2=default2, arg3): # e.g., power (x, y=3) body

  3. Function with docsting

  4. Function modifies a string

  5. Pass arguments by position

  6. Casting user’s entered value

  7. Function traverses a string with a loop

  8. 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

  9. 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

  10. Find maximum of any unknown set of arguments Notice that the function is called with different numbers of arguments. The * does the trick!

  11. Defining a global variable Notice that calling the local variable outside of the function leads to error!

  12. Assigning the returned value of a function to a variable

  13. 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

  14. 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”)

  15. 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

  16. 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.

  17. 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

  18. 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

  19. 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 string r”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”

  20. Absolute path vs. relative path • Absolute path is the exact address of the file in the filesystem, starting from the root. C:\Geoinformatics\myFile.txt A:\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.

  21. 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” orcwd for a program. • Do the following to get the cwd of Python on your computer

  22. Opening files in read mode

  23. Opening a file in the write mode • We pass ‘w’ instead of ‘r’ in the 2ndargument • This will first erase data in the file before writing. • NOTE: If we want to append to the file, use ‘a’ instead of ‘w’.

  24. Open File example for ArcGIS >>> f = open ("C:/Data/mytext.txt", "w") >>> f.write ("GIS") >>> f = open ("C:/Data/mytext.txt", "r") >>> f.read() 'GIS‘

  25. Read the number of lines in a file • Assume the multi_line.txt file has five words written in five lines

  26. Screen input/output Input () is a built-in method to prompt for input; returns a string

  27. 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

  28. Raising (throwing) an exception try : # 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).

  29. 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

  30. 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 executed exception 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 on else : # iff there is no error, come here, this is optional, and rarely used else_body finally : # optional. If it exists, it always executes finally_body# clean up by closing files or resetting variables

  31. Common exception errors and examples • IOErrorIf the file cannot be openedor read. print (“Error while reading the file”) • ImportErrorIf python cannot find the module print (“no module found”) • ValueErrorRaised when a built-in operation or function receives an argument that has the right type but an inappropriate value print (“non-numeric data found”) • KeyboardInterruptRaised when the user hits the interrupt key (normally Control-C or Delete) print (“you cancelled the operation”) • EOFErrorRaised 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”)

  32. HandleValueError

  33. Assign exception to variable

  34. HandleValueError … • 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

  35. 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 x 6 >>> x = list[4] # this raises the ‘list index out of range’ error Traceback(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!

  36. Catching when knowing the type of error

  37. Catching multiple error types

  38. IOError

  39. Handle opening file issues • We use try/except for quality assurance (QA)

  40. IOError …

  41. IOError …

  42. Catch all exception types

  43. 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.

More Related