Geoscience Reference
In-Depth Information
The first line indicates that the Python interpreter should be used. Note that it could
equally be
/usr/bin/python
and that it is possible to specify different Python
versions (e.g. 2.7 or 3) depending on your computing environment and configuration.
It is also recommended to include some comments at the beginning of the script as
this metadata will be useful to you, when you re-visit your program as well as to
other users or developers. Depending on the license, it may be useful to include the
GPL header that is described on the GNU website.
10
•
Program name and description
•
Author/Developer's name
•
Version Number
•
Copyright
•
Usage (i.e. Example of code execution, including flags).
In order to access OGR from Python, it is necessary to import the OGR module
to allow access to its public functions, methods and classes. Depending on your
distribution, the
ogr
module can be located in different locations, so to overcome
this, we include a
try
statement to test two different locations. In addition to
ogr
we include other common modules that you will probably want to use are
sys
and
os
. We will also include the
numpy
,
matplotlib
and
argparse
modules. The
latter module provides support for command line options being passed to the script.
#!/usr/bin/python2.7
"""PlotVector.py
This Python program plots a vector Shapefile using the OGR
and Matplotlib libraries. It accepts two command line options,
which are datasource path/filename and display color.
"""
__author__ = "Name of Developer"
__version__ = "$Version: 1.0 $"
__date__ = "$Date: 2014/29/04 08:44:23 $"
__copyright__ = "Copyright (c) Include if applicable"
We begin our Python program by defining a
def main()
function, where we
will import the modules that we need, namely:
ogr
,
argparse
and
matplotlib
.
We setup the option parser to accept two options on the command line: the dataset
name and the color used to plot the vector. Adding these options to the script makes
it more flexible and dynamic, rather than having to hard code options. Hard coding
means that the script would need to be edited each time the user wanted to change the
name of the input file. Note that we provide two ways of specifying the options, either
using the long option name preceded by a double hyphen, i.e.
—-datasource
or
using a short option preceded by a single hyphen
-d
.
Search WWH ::
Custom Search