10. Python Scripting

Python is a robust programming language that provides many different features that you would expect from a modern language. One of its many benefits is the fact that it is object-oriented by nature, making it a good language for large task programs.

This chapter’s focus is to give you a firm understanding of how to write basic Python scripts as well as provide you with an understanding of some of Python’s more advanced features.

Basics of Python Scripting

Unlike Perl (discussed in Chapter 9, “Perl Scripting”), Python is very much a structured language. It is very sensitive to white space, to the point that improper white space usage causes a program to crash with compile errors.

When you create a block of code, you must indent the entire block with the same number of white space characters. For example, consider the following code fragment, focusing on how the code is indented:

x = 25
if x > 15:

     print x
     a = 1
else:

print x
      a = 2

The preceding code fragment results in a compile time error message because the second print statement isn’t properly indented. The positive thing about enforced structure is that it makes your code easier to read (for both others and yourself when you look over code that you wrote months or years ago). The negative thing is that it can be a pain when you miss a space or accidently use a tab instead of four spaces.1


Use an Editor to Avoid Indentation Issues

To avoid issues with indentation, use an editor designed to perform auto indentation. Many such editors are designed specifically for Python, but you can also use a generic editor such as vim.

To enable auto indentation in vim, start the editor and then execute the command :set autoindent. Bonus: If you edit a file that ends with .py, the vim editor will color code key Python statements.


Executing Python Code

Currently, the two primary versions of Python are 2.x and 3.x. At the time of the writing of this book, version 2.x was the more popular of the two, so the book covers 2.x syntax. To determine which version of Python is installed on your Linux distribution, execute the python command with the -V option or enter the Python interactive shell by executing the python command with no arguments:

[student@OCS ~]$ python
Python 2.7.5 (default, Oct 11 2015, 17:47:16)
[GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> quit()
[student@OCS ~]$

Note that the python command not only displays the version of Python, but it also places you into an interactive Python shell where you can test Python code on the fly. To exit this Python shell, enter the quit() statement as shown in the previous example.

To execute a Python script that is stored in a file, use the following syntax:

[student@OCS ~]$ python script.py

Typing the python command before each execution can become annoying. To avoid that, make use of the #! line:

[student@OCS ~]$ more hello.py
#!/bin/python

print "hello"
[student@OCS ~]$ chmod a+x hello.py
[student@OCS ~]$ ./hello.py
hello

As demonstrated from the previous example, the print statement in Python is used to produce output. By default, this output goes to STDOUT.


A Note about .pyc and .pyo Files

Your Python script names should end with .py. You will sometimes also see files that end in .pyc, and this can lead to some confusion. Not touching these files is best because they are compiled versions of Python code and not something that you can edit directly.

These files are created when a Python library is called. The idea is that the compile process takes time and each time a library is called, its code would have to be compiled. To make the process more efficient, Python automatically saves this code into files that end in .pyc. So, if you call a library called input.py, you should expect to see a file called input.pyc after the program that calls the library is executed.

When Python is invoked with the -O option, a .pyo file is generated. Like .pyc files, this is compiled code, but it is optimized complied code.


Additional Documentation

Initially you probably want to look at the man page for python: man python. This provides you with some of the basics of the python executable, but there isn’t much focus on how to write code in Python.

However, at the bottom of the python man page are some very useful links to additional documentation, as shown in Figure 10.1.

Figure 10.1 Python documentation

The URL http://docs.python.org/ will likely be the most useful resource when you start learning Python, but the other links will also prove valuable over time.

Variables and Values

Python has several data structure types, including:

Numeric variables—A single data type that is used to store numeric values.

String variables—A single data type that is used to store string values.

Lists—An ordered list of numeric or string values.

Dictionaries—A collection of unordered values that are referenced by using a key.

Numbers and strings are different in that you can perform certain operations on numbers (addition, subtraction, and so on) but not on strings as demonstrated in Listing 10.1.


Listing 10.1 Numbers versus strings

[student@localhost Desktop]$ python
Python 2.7.5 (default, Oct 11 2015, 17:47:16)
[GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a=100
>>> print a
100
>>> b=200
>>> print a + b
300
>>> c="hello"
>>> print a + c
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'


Note the error that occurred in the last statement of Listing 10.1 when the string variable was used in a numeric operation.

Python has a rich set of operations that can be performed on strings. For example, you can use the following to capitalize a string:

>>> name="ted"
>>> name=name.capitalize()
>>> print name
Ted

Python is an object-oriented language. Variables store typed objects (numeric type, string type, and so on), and to call a method on an object, you use the notation var.method(). So, name.capitalize() calls the capitalize method on the object in the name variable.

Note that Python has a few traditional functions as well. For example, consider the following code:

>>> name="ted"
>>> print len(name)
3

The len function takes an object as an argument and returns the length of the object. Granted, using both method calls and functions can sometimes be confusing, but keep in mind that most of Python consists of method calls, and functions are fairly rare.

To create a list, use the following syntax:

>>> colors=["red", "blue", "yellow", "green"]
>>> print colors
['red', 'blue', 'yellow', 'green']

Use the following notation to access elements in a list:

>>> colors=["red", "blue", "yellow", "green"]
>>> print colors[1]
blue
>>> print colors[1:3]
['blue', 'yellow']

Important methods that manipulate lists include the following:

append—Adds a new element to the end of the list.

insert—Adds a new element to a specific position in the list.

extend—Adds the elements of a list to another list.

del—Removes an element from a list based on an index position.

pop—Removes the last element from a list.

remove—Removes an element from a list based the value of the element.


The Tuple

You are likely to come across another data structure that works much like a list called a tuple. Consider a tuple to be a list that, once created, can’t be modified. Technically, tuples are immutable, a fancy way of saying unchangeable. They are a clever way of having constant-like data structures.


To create a dictionary in Python, use the following syntax:

>>> age={'Sarah': 25, "Julia": 18, "Nick": 107}
>>> print age
{'Sarah': 25, 'Nick': 107, 'Julia': 18}
>>> print age['Sarah']
25

To add a key-value pair to a dictionary, use the following syntax:

>>> age['Bob']=42

Times occur when you will want to get a list of all the keys of a dictionary. To accomplish this, use the keys() method:2

>>> age={'Sarah': 25, "Julia": 18, "Nick": 107}
>>> print age.keys()
['Sarah', 'Nick', 'Julia']


Other Data Structures

Python has other data structures that you should consider exploring. For example, you can create sets of data within Python. This is useful because set objects have methods that enable you to find items that appear in two sets or items that only appear in a specific set.


Flow Control

Python supports many traditional flow control statements, including the if statement:

age=15
if age >= 16:
    print "you are old enough to drive"
elif age == 15:
    print "you are old enough for a permit"
else:
    print "sorry, you can't drive yet"

Another common conditional statement is the while loop. With the while loop, a conditional check is performed and, if the condition is true, a block of code is executed. After the block of code is executed, the conditional check is performed again. See Listing 10.2 for an example.


Listing 10.2 The while loop

#!/bin/python

age = int(raw_input('Please enter your age: '))

while (age < 0):

    print "You can't be that young!";
    age = int(raw_input('Please enter your age: '))

print "Thank you!";


Note that in Listing 10.2, the raw_input() function gets data from the user (STDIN, likely the keyboard) and the int() function converts this data into an integer object.

To perform an operation on each item of a list, use the for loop:

>>> colors=["red", "blue", "yellow", "green"]
>>> for hue in colors:
...    print hue
...
red
blue
yellow
green

Many languages support loop control statements such as break and continue. Python has these statements, which you can use in while loops or for loops. The break statement exits the loop prematurely and the continue statement stops the current iteration of the loop and starts the next iteration. Python also supports an else statement that you can use to execute additional code if the loop is terminated without a break statement.

Conditions

Python supports a large variety of conditional expressions, which enable you to perform comparison operations on like objects. For example, you can compare strings to strings, dictionaries to dictionaries, and so on.

Comparison operators include the following:

== Determine whether two objects are equal to each other.

!= Determine whether two objects are not equal to each other.

< Determine whether one object is less than another object.

<= Determine whether one object is less than or equal to another object.

> Determine whether one object is greater than another object.

>= Determine whether one object is greater than or equal to another object.

Additional Features

In addition to reading from the keyboard, you can open files and read directly from the files. For example:

>>> data=open('test.py', 'r')
>>> print data
<open file 'test.py', mode 'r' at 0x7f4db20ba1e0>

The first argument to the open statement is the filename to open. The second argument is how to open it. The value 'r' means to open the file for reading. You can also open a file and write to the file by using the value of 'w'.

You can use several methods for reading from and writing to a file after opening it:

read()—Reads the entire file. Example: total = data.read().

readline—Reads one line from the file.

write—Writes data to a file. Example: data.write("hello").

Another important feature in Python is functions. To create a function, use the following syntax:

def welcome():
   print "This is my function"

You can call a function by using the following syntax:

welcome()

To reuse code in other programs, Perl has a feature called modules. By calling a module, you have access to functions that are shared by that module in your program.

For example, the following module call provides a function called path that displays a list of directories where Python libraries are held:

>>> import sys
>>> print sys.path
['', '/usr/lib64/python27.zip', '/usr/lib64/python2.7', '/usr/lib64/python2.7/plat-linux2', '/usr/lib64/python2.7/lib-tk', '/usr/lib64/python2.7/lib-old', '/usr/lib64/python2.7/lib-dynload', '/usr/lib64/python2.7/site-packages', '/usr/lib64/python2.7/site-packages/gtk-2.0', '/usr/lib/python2.7/site-packages'] /home/student


Programming Humor

Definition of recursion:

1.  Stop when you understand the definition.

2. See definition of recursion.


Summary

This chapter serves as an introduction to the Python language. As with most languages discussed in this book, Python offers many other features. The purpose of this chapter was to introduce you to the language to determine whether it might meet your software development needs.

1 You might be thinking, “Why did he say four spaces and not five or eight?” Python Enhancement Proposals (PEPs) are a major component of Python development. PEP8 is the “Style Guide for Python Code,” and it states that the standard for indentation is four spaces.

2 Note that the return value of the keys are not in the order they were originally created in. Remember that a dictionary is an unordered collection of key-value pairs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.8.247