Intro To Python
Intro To Python
• geoprocessing
• why this course uses Python
• where to write code
• input to scripts
• basic Python code components
Dr. Tateosian
In-class exercise
arcpy.env.workspace = 'C:/gispy/data/ch01/‘
arcpy.Buffer_analysis('park.shp',
'C:/gispy/scratch/parkBuffer.shp', '0.25 miles',
'OUTSIDE_ONLY', 'ROUND', 'ALL') 2
ESRI Geoprocessing
Export
models to
scripts
Call scripts
from models
•Automate tasks.
•Batch processing.
•Schedule processes.
•Intuitive syntax.
•Coverity report:
• http://wpcme.coverity.com/wp-content/uploads/2013-Coverity-Scan-Spotlight-Python.pdf
4
Where to write code?
5
PythonWin Interface
Menus
Toolbars
debugging, standard
Script window
Write and save code
(permanent)
Interactive window
Test lines of code
Report messages
(temporary)
Feedback 6
Syntax error or success
PythonWin standard toolbar
Standard toolbar
7
‘add.py’ example, line by line
a = int(sys.argv[1])
b = int(sys.argv[2])
c = a + b
print “The sum is”, c
Concepts:
• # means what follows on that line is a comment just for human readers
• import sys (lets you use things from the sys module)
• variables (a and b are variables; they are assigned values with “=“ )
• sys.argv (argument vector; the list of things you send in when you run it)
• int (converts a string to an integer)
• print
8
In-class: Run add.py in PythonWin
• Open the program add.py
• Run the program or Ctrl+R
Output:
The sum is 11
sys.argv[1] + sys.argv[2] = 56 WHY?
• Uncomment the bottom sys.argv[0] = C:\<my directory path>\add.py
Select and click (Alt + 4) sys.argv[1] = 5
Run again. sys.argv[2] = 6 9
What do you see?
10
Python components • Variables
• Comments
• Keywords
• Modules
• Indentation
• Objects
• Functions
• Built-ins
• Assignment
statements
• Data structures
Syntax highlighting:
text color/font based on code features 11
Basic building blocks
12
Commenting code
# conditional_addfield.py
Header
# Purpose: Add a field, if it does not already exist.
(documentation
# Usage: field_name
comments)
# Example input: “bridges”
# Output: A shapefile with the new field added, if it didn’t already exist.
# Author: Donald Duck 8/22/2065
# Modified: Silvester 3/06/2080 to run in PythonWin
13
Python Keywords
• Examples:
• ‘radians’ is a ‘math’ module function:
15
Variable naming rules & conventions
• Variables are case sensitive
freeways = “Freeways.shp”
Freeways = 20000
• tableFieldName = “Street”
17
Python Objects
• Everything in Python is an Object
• Each object has:
• A value data item represented by
an object
• An Identity unique identifier, similar
to a memory address
>>> river = "Arno“ • A Type specifies what kind of values
>>> river an object can hold and which
'Arno‘ operations are allowed
>>> id(river)
15446688
>>> type(river)
<type 'str'>
>>> river = 96 Dynamically typed variables
>>> type(river)
<type ‘int’>
18
Python built-in Functions
19
Functions
>>> round(1.7) >>> min(1, 2, 3)
2.0 1
>>> help(min)
Help on built-in function min in module __builtin__:
min(...)
min(iterable[, key=func]) -> value
min(a, b, c, ...[, key=func]) -> value
With a single iterable argument, return its smallest item.
With two or more arguments, return the smallest
argument.
Parameter vs. argument
• the built-in help function prints a template (a signature).
• the signature lists the parameters
• parameter – piece of info. passed in to a function
>>> help(round)
Help on built-in function round in module __builtin__:
round(...)
round(number[, ndigits]) -> floating point number
argument arguments 22
Built-in constants
• Values assigned as soon as Python is launched
• Examples: True, False, None
>>> type(True)
<type 'bool'>
>>> True
True
•Geoprocessing example:
>>> import arcpy
>>> arcpy.env.overwriteOutput = True
23
Built-ins exceptions
• Exceptions: common errors that Python can identify automatically.
24
In class: tryMe
25
‘tryMe’ take home lessons
>>> type(min)
<type 'builtin_function_or_method'>
>>> min(1, 2, 3)
1
>>> min = 5
>>> min(1, 2, 3)
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: 'int' object is not callable
>>> type(min)
<type 'int'>
26
Summing up
• Topics discussed
• Why use Python
• Integrated development environments (IDEs)
• Passing arguments into scripts
• Basic Python code components: naming & initializing variables,
comments, keywords, modules, indentation, objects, functions, built-ins
functions, constants, exceptions, assignment statements, data structures
• Up next
• Data structures: integers, floats, strings, lists, tuples…
27
Appendix
28
Extra exercise – Exporting a module
• ModelBuilder models can be exported to Python scripts.
• Right click on Model >
Model menu > Export > To Python Script…
30
Export from modified model
exported2.py
Once the output has been created, it won’t overwrite it, unless told to do so as follows:
arcpy.overwriteOutput = True
‘Exporting a model’ exercise take home message: Yes, you can export them,31