Modules and Functions - Reiteration and clarity is needed ...



3W - Geography 465 – Reviewing Object Types, Functions, and Modules

A review is in order for objects, functions, and modules – just as a status check for where we are in Python. Below we review some highlights about what we have seen so far: built-in object types, functions __builtins__, and modules os, os.path, sys, string, math, time, calendar, webbrowser, win32com (win32com.client)

A typical start of a python script:

#Import standard library modules

import win32com.client, sys, os

gp = win32com.client.Dispatch(“esriGeoprocessing.GpDispatch.1”)

- This imports the system, operating system, and Windows 32 modules to the script.

- The sys module refers to the Python system and will be used to access user-specified inputs.

- os module provides easy access to the most fundamental tools of the operating system.

- Some of the os module’s filename manipulation tools are used in this script.

- gp can be used to access all geoprocessing functionality through this variable

We can use ArcGIS Desktop Help to access scripts – in the content window navigate to…for example “point distance” (see bottom of image)

[pic]

[pic]

Built-in Object types – make programming easier (Table 4-1, LP p. 55).

Object type Example

Numbers 3.1415, 1234, 999L, 3+4j

Strings ‘spam’, “guido’s”

Lists [1, [2, ‘three’], 4] # ordered collections of objects; index start at 0

Dictionaries {‘food’: ‘spam’, ‘taste’: ‘yum’} # collections of objects indexed by key

Tuples (1, ‘spam’, 4, ‘U’) # ordered set, not indexed

Files text = open(‘eggs’, ‘r’).read()

Reading for above, LP list pp 97-99, dictionary pp 103-4, tuples pp 112-4

assignments LP pp 68, 134-40 p 135 Table 8-2

Operation Interpretation

spam = ‘Spam’ # basic form

spam, ham = ‘yum’, ‘YUM’ # tuple assignment

[spam, ham] = ‘yum’, ‘YUM’ # list assignment

Spam = ham = ‘lunch’ # multiple target

Boolean/truth values LP pp 154, 122-3 Table 7-4 p 122

Object Value

“spam” True

“” False

[] False

{} False

1 True

0.0 False

None False

type hierarchies LP p 124 Figure 7-3

if..then pp 146-148

if : # if test

# Associated block

elif : # Optional elifs

# Associated block

else: # Optional else

# Associated block

while Loops LP pp 155-6

while : #Loop test

# Repeated body

else: # Optional else

# Perform when break is hit

for Loops LP pp 160-2

for in : #Assign object items to target

# Repeated body: use target

else:

# If break not hit

try...except LP pp 393-5

catch and recover from exceptions raised by Python, or by user/programmer

>>> try:

… fetcher(x,4)

… expect IndexError:

… print ‘got exception’



got exception

>>>

The try statement defines the beginning of a block of code that will be handled by its associated exception handler, or except statement. It is good practice to use exception handling in any script using the geoprocessor so its error messages can be propagated back to the user. This also allows the script to exit gracefully and return informative messages instead of simply causing a system error.

Built-in Functions - Standard functions that are 'on' when Python starts.



There are many useful for basics, but would likely need more. A selection might include:

max(s[, args...])

min(s[, args...])

open(filename[, mode[, bufsize]])

range([start,] stop[, step])

range([start,] stop[, step])

raw_input([prompt])

tuple(sequence)

Modules – foster code reuse; a way to package code; important instructions for modules:

import – fetches a module as a whole

from – fetches a particular names from a module

reload – reload a module’s code without stopping Python (actually a built-in function)

The os and sys modules are important for getting Python to integrate and manage with the local os and system.

os Module - Miscellaneous OS interfaces



This module provides a more portable way of using operating system (OS) dependent functionality than importing an OS dependent built-in module to enhance portability.

os.path Module - Common pathname manipulations



This module implements some useful functions on pathnames.

Subsections

• 6.1.1 Process Parameters

• 6.1.2 File Object Creation – important

• 6.1.3 File Descriptor Operations – important

• 6.1.4 Files and Directories – particularly important: directory settings, working directories and disk operations, e.g., chmod, mkdir, chdir

• 6.1.5 Process Management

• 6.1.6 Miscellaneous System Information

sys Module - System-specific parameters and functions



This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It is always available.

In what way are these functions significant to your programming effort?

string Module - Common string functions (operations)



Many functions of the string module are built-in, especially with the more current releases. However, getting more detailed with strings might require importing the string module.

Which of these functions would you never think you would use in a GIS application?

math Module - Mathematical functions



This module is always available. It provides access to the mathematical functions defined by the C standard.

In what data processing context might these functions come in handy?

time Module - Time access and conversions



This module provides various time-related functions. It is always available, but not all functions are available on all platforms.

For what kinds of applications might you use one or more functions from this module?

calendar Module - General calendar-related functions



This module allows you to output calendars, and provides additional useful functions related to the calendar. By default, these calendars have Monday as the first day of the week, and Sunday as the last (the European convention). Use setfirstweekday() to set the first day of the week to Sunday (6) or to any other weekday.

How might we use the calendar in a GIS application? GIS software often does not implement the time aspect of data (space, attribute, time). Examine the GP model diagram. What calendar functions do you have available through it?

webbrowser Module - Convenient Web-browser controller



The webbrowser module provides a very high-level interface to allow displaying Web-based documents to users.

Why would we need a webbrowser for a gp application?

Tkinter (Tk module) pp 496-8 – a forms editor interface

The Tkinter toolkit is a Python-specific interface to a non-Python GUI library called Tk. Tk is the GUI toolkit most commonly chosen by Python programmers because it provides professional-looking GUIs within a fairly easy-to-use system. In addition, the Python/Tk interface comes with most Python distributions. Although the interfaces are not exactly like Mac, Windows or Unix, they are close look alikes.

Insights and precautions for win32com

Scripting with win32com, win32com.client and Dispatch in 9.1 versus 9.2



ArcGIS 9.1 included PythonWin 2.1 as the default editor. ArcGIS 9.2 does ship with PythonWin 2.4.1, however it is not included in the installation. There are two reasons why PythonWin 2.4.1 is not included in the installation. First off, there was a change in the PythonWin 2.4.1 installer that made it incompatible with the ArcGIS installer. Secondly, PythonWin is not required for Python scripts to run as it was in 9.1.

The win32com package

Document describes the win32com package in general terms. The COM support can be thought of as existing in 2 main portions - the C++ support code (the core PythonCOM module), and helper code, implemented in Python. The total package is known as "win32com".



Win32Com Readme



Win32Com doorway

In every script that calls the gp, the win32com is the doorway into the gp. It is specific to PythonWin, but provides the impression that it isn't required when using IDLE as the code editor. A power to knowing more about the module is an ability to interact with other programs like Word, Excel, browsers and the like.

A quest for a more complete list of essential modules that enable or extend Python's relations with the gp should look into the ArcGIS desktop help files. There are 1000's of scripts and script examples that have the classic gp=win32com.client along with imports of other modules used at those times.

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download