Chapter P11. An overview on Python

Goals for this chapter:
  • python (python)
  • make (make)
  • cc (cc)
  • strip (binutils)
  • touch (fileutils)

 
python, (Gr. Myth. An enormous serpent that lurked in the cave of Mount Parnassus and was slain by Apollo)
1. any of a genus of large, non-poisonous snakes of Asia, Africa and
Australia that suffocate their prey to death.
2. popularly, any large snake that crushes its prey.
3. totally awesome, bitchin' language that will someday crush the $'s out of certain other
                                    so-called VHLL's ;-) .

 
 

What is Python ?


In 1990 Guido van Rossum invent Python at Centrum voor wiskunde en Informatica (CWI) in Amsterdam. Today, he works for the Corporation for National Research Initiatives (CNRI) in Reston Virginia (USA).

Like Linux, X Window, TeX and other Linux components, Python is a Universe. You can develop applications to generate curses (text-based), graphical, HTML, XML, DHTML, etc. There are also browsers written in Python and you can also use Python in MSWindows, etc.

Python born like a programming language for write and testing administration scripts.

The Guido's ideas comes from the ABC project, a CWI programming language for non-technical users, modula-2 and modula-3 and the C language.

You can also runs python, similar to the Tcl shell (tclsh).

[root@ftosx1 Python]# python
Python 1.5.2 (#1, Jul  5 2001, 03:02:19)  [GCC 2.96 20000731 (Red Hat Linux 7.1 2 on linux-i386
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> a=1
>>> b=2
>>> print a+b
3
>>>
[root@ftosx1 Python]#

Python also support complex numbers ... using classes!

[root@ftosx1 /root]# python
Python 1.5.2 (#1, Feb  1 2000, 16:32:16)  [GCC egcs-2.91.66 19990314/Linux (egcs- on linux-i386
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> a=2+3j
>>> a.real
2.0
>>> a.imag
3.0
>>>
 

The RedHat Team probably made the better use of Python in the Linux OS, actually. We list here only some of the most important programs that uses python:

For example, netcfg runs a python script located in "/usr/lib/rhs/"

[root@ftosx1 /root]# which netcfg
/usr/bin/netcfg
[root@ftosx1 /root]# more /usr/bin/netcfg
#!/bin/sh

export PYTHONPATH=/usr/lib/rhs/netcfg:/usr/lib/rhs/python

exec python /usr/lib/rhs/netcfg/netcfg.py
[root@ftosx1 /root]#

Python is also equivalent to PERL language in the programming style and also in the results. For this reason, both languages are planned to mix in a new programming language called Parrot; however mo major updates had been made in more than one year.

Note for example the following code:
 

[root@ftosx1 Python]# more rpmlist.py
#!/usr/bin/python
import string, os, HTMLgen

allrpms = "rpm -q -a --queryformat '%{group} \
%{name} %{summary}\n'"

inpipe  = os.popen(allrpms, "r")
rpmlist = inpipe.readlines(); inpipe.close()
rpmlist.sort()

indexfile="rpm.html"
mainfile="rpmlist.html"

idoc = HTMLgen.SeriesDocument("rpmstyle.rc")
mdoc = HTMLgen.SeriesDocument("rpmstyle.rc")

ilist = HTMLgen.List(style="compact", columns=3)
idoc.append(ilist)

lastgroup = ""
for rpm in rpmlist:
    fields = string.split(rpm)
    group, name = (fields[0], fields[1])
    summary = string.join(fields[2:], " ")
    if group != lastgroup:
        lastgroup = group
        title = HTMLgen.Text(group)
        href  = HTMLgen.Href(mainfile+"#"+ group,
                             title)
        ilist.append(href)
        anchor = HTMLgen.Name(group, title)
        mdoc.append(HTMLgen.Heading(2, anchor))
        grplist = HTMLgen.DefinitionList()
        mdoc.append(HTMLgen.Blockquote(grplist))
        grplist.append(
       (HTMLgen.Text(name),HTMLgen.Text(summary)))

idoc.write(indexfile)
mdoc.write(mainfile)

[root@ftosx1 Python]#

Note that this mode is very similar to PERL coding. The HTMLgen, in the previous version is a "external packages" developed in Python.
 

My first program in Python

Here we will develop very simple programs. At the same time we will introduce the most common python data types and how to use it.

Numbers

As explained in the previous section python support complex numbers.

While to work with complex numbers we will need the "cmath" module, please check:

[root@ftosx1 examples]# python
Python 1.5.2 (#1, Jul  5 2001, 03:02:19)  [GCC 2.96 20000731 (Red Hat Linux 7.1 2 on linux-i386
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> import cmath
>>> a=1+1j
>>> b=cmath.sqrt(a)
>>> b.real
1.09868411347
>>> b.imag
0.455089860562
>>>
[root@ftosx1 examples]#

To work with real we will need only the "math" module.

To know what functions are listed or included in a determinated module, we can use "dir()" function.

[root@ftosx1 examples]# python
Python 1.5.2 (#1, Jul  5 2001, 03:02:19)  [GCC 2.96 20000731 (Red Hat Linux 7.1 2 on linux-i386
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> import cmath
>>> dir(cmath)
['__doc__', '__file__', '__name__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cos', 'cosh', 'e', 'exp', 'log', 'log10', 'pi', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']
>>>

By default, only three modules are loaded.

[root@ftosx1 examples]# python
Python 1.5.2 (#1, Jul  5 2001, 03:02:19)  [GCC 2.96 20000731 (Red Hat Linux 7.1 2 on linux-i386
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> dir()
['__builtins__', '__doc__', '__name__']
>>>
 

Strings

Python supports strings basically how C++, but in a script enviroment. This is basically very usefull.

[root@ftosx1 examples]# python
Python 1.5.2 (#1, Jul  5 2001, 03:02:19)  [GCC 2.96 20000731 (Red Hat Linux 7.1 2 on linux-i386
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> 'Hello'
'Hello'
>>> "Hello"
'Hello'
>>> 'Hello World'
'Hello World'
>>>

Now, we will do some math on the strings.

[root@ftosx1 examples]# python
Python 1.5.2 (#1, Jul  5 2001, 03:02:19)  [GCC 2.96 20000731 (Red Hat Linux 7.1 2 on linux-i386
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> a="Hello"
>>> b="World"
>>> c=a+b
>>>
>>> c
'HelloWorld'
>>>

The previous statements was made without any module. However, a module called "string" is available.

>>> import string
>>> dir(string)
['__builtins__', '__doc__', '__file__', '__name__', '_idmap', '_idmapL', '_lower', '_re', '_safe_env', '_swapcase', '_upper', 'atof', 'atof_error', 'atoi', 'atoi_error', 'atol', 'atol_error', 'capitalize', 'capwords', 'center', 'count', 'digits', 'expandtabs', 'find', 'hexdigits', 'index', 'index_error', 'join', 'joinfields', 'letters', 'ljust', 'lower', 'lowercase', 'lstrip', 'maketrans', 'octdigits', 'replace', 'rfind', 'rindex', 'rjust', 'rstrip', 'split', 'splitfields', 'strip', 'swapcase', 'translate', 'upper', 'uppercase', 'whitespace', 'zfill']
>>>

Lists

Like Tcl, python supports lists.

Here we have a simple and effective example.

>>> l = ['Apple', 'Microsoft', 'Cisco', 'Intel']
>>> l
['Apple', 'Microsoft', 'Cisco', 'Intel']
>>> l[0]
'Apple'
>>>
>>> l[3]
'Intel'
>>>
>>> l[-2]
'Cisco'
>>>

Therefore the range is intended as a cyclical range where elements will rotate around the first.

Also range in the index, are supported.

>>> l[1:-3]
[]
>>> l[1:3]
['Microsoft', 'Cisco']
>>> l[0:3]
['Apple', 'Microsoft', 'Cisco']
>>> l[0:4]
['Apple', 'Microsoft', 'Cisco', 'Intel']
>>>
>>> len (l)
4
>>

We can also insert elements in any position.

>>> l[5:6]=['IBM', 'Future Technologies']
>>> l
['Apple', 'Microsoft', 'Cisco', 'Intel', 'IBM', 'Future Technologies']
>>>
 

Dictionaries

Python includes different original and innovative data containers.

For example, it is possible to connect to a two different "rows" of information in a single data abstraction type called: dictionaries.

       >>> tel = {'jack': 4098, 'sape': 4139}
       >>> tel['guido'] = 4127
       >>> tel
       {'sape': 4139, 'guido': 4127, 'jack': 4098}
       >>> tel['jack']
       4098
       >>> del tel['sape']
       >>> tel['irv'] = 4127
       >>> tel
       {'guido': 4127, 'irv': 4127, 'jack': 4098}
       >>> tel.keys()
       ['guido', 'irv', 'jack']
       >>> tel.has_key('guido')
       1
 

This is simple mode to use and define a simple datatype without to use or access Database.

PERL includes a similar approach.
 

Classes

Python supports classes, basically like C++ or as any OOJ programming language.

For example the power that python offer to us on "strings" and "complex number" manipulation is possible for a class implementation.

Here we define a new class.

class Employee:
           pass

       john = Employee() # Create an empty employee record

       # Fill the fields of the record
       john.name = 'John Doe'
       john.dept = 'computer lab'
       john.salary = 1000
 

On complex numbers we define:
 

       >>> class Complex:
       ...     def __init__(self, realpart, imagpart):
       ...         self.r = realpart
       ...         self.i = imagpart
       ...
       >>> x = Complex(3.0,-4.5)
       >>> x.r, x.i
       (3.0, -4.5)
 
 

File I/O with Python

Python supports also I/O function on files.

       >>> f=open('/tmp/workfile', 'r+')
       >>> f.write('0123456789abcdef')
       >>> f.seek(5)     # Go to the 5th byte in the file
       >>> f.read(1)
       '5'
       >>> f.seek(-3, 2) # Go to the 3rd byte before the end
       >>> f.read(1)
       'd'

Its approach is simple and innovative ... 100% equivalent to C language but on scripts.
 

The conditionals and cycle in Python development are very simple and immediate.

The Standard Python Library

We call the Standard Python Library the complete set of Python modules, released with the python package.

We can list here these modules for the 2.1 library.

[root@ftosx1 python2.1]# ls -F *o
aifc.pyo            cmd.pyo           dospath.pyo         htmllib.pyo      mimetools.pyo   posixfile.pyo     repr.pyo              socket.pyo         tabnanny.pyo   UserDict.pyo
anydbm.pyo          codecs.pyo        dumbdbm.pyo         httplib.pyo      mimetypes.pyo   posixpath.pyo     re.pyo                SocketServer.pyo   telnetlib.pyo  UserList.pyo
asynchat.pyo        codeop.pyo        filecmp.pyo         ihooks.pyo       MimeWriter.pyo  pprint.pyo        rexec.pyo             sre_compile.pyo    tempfile.pyo   user.pyo
asyncore.pyo        code.pyo          fileinput.pyo       imaplib.pyo      mimify.pyo      pre.pyo           rfc822.pyo            sre_constants.pyo  TERMIOS.pyo    UserString.pyo
atexit.pyo          colorsys.pyo      fnmatch.pyo         imghdr.pyo       multifile.pyo   profile.pyo       rlcompleter.pyo       sre_parse.pyo      threading.pyo  uu.pyo
audiodev.pyo        commands.pyo      formatter.pyo       imputil.pyo      mutex.pyo       pstats.pyo        robotparser.pyo       sre.pyo            toaiff.pyo     warnings.pyo
base64.pyo          compileall.pyo    fpformat.pyo        inspect.pyo      netrc.pyo       pty.pyo           sched.pyo             statcache.pyo      tokenize.pyo   wave.pyo
BaseHTTPServer.pyo  ConfigParser.pyo  ftplib.pyo          keyword.pyo      nntplib.pyo     pyclbr.pyo        sgmllib.pyo           stat.pyo           token.pyo      weakref.pyo
Bastion.pyo         Cookie.pyo        __future__.pyo      knee.pyo         ntpath.pyo      py_compile.pyo    shelve.pyo            statvfs.pyo        traceback.pyo  webbrowser.pyo
bdb.pyo             copy.pyo          getopt.pyo          linecache.pyo    nturl2path.pyo  pydoc.pyo         shlex.pyo             StringIO.pyo       tty.pyo        whichdb.pyo
binhex.pyo          copy_reg.pyo      getpass.pyo         locale.pyo       os.pyo          Queue.pyo         shutil.pyo            stringold.pyo      types.pyo      whrandom.pyo
bisect.pyo          dbhash.pyo        gettext.pyo         macpath.pyo      pdb.pyo         quopri.pyo        SimpleHTTPServer.pyo  string.pyo         tzparse.pyo    xdrlib.pyo
calendar.pyo        difflib.pyo       glob.pyo            macurl2path.pyo  pickle.pyo      random.pyo        site.pyo              sunaudio.pyo       unittest.pyo   xmllib.pyo
CGIHTTPServer.pyo   dircache.pyo      gopherlib.pyo       mailbox.pyo      pipes.pyo       reconvert.pyo     smtpd.pyo             sunau.pyo          urllib2.pyo    zipfile.pyo
cgi.pyo             dis.pyo           gzip.pyo            mailcap.pyo      popen2.pyo      regex_syntax.pyo  smtplib.pyo           symbol.pyo         urllib.pyo
chunk.pyo           doctest.pyo       htmlentitydefs.pyo  mhlib.pyo        poplib.pyo      regsub.pyo        sndhdr.pyo            symtable.pyo       urlparse.pyo
[root@ftosx1 python2.1]#
 

One of this is the "sys" module.

[root@ftosx1 Python]# python
Python 1.5.2 (#1, Jul  5 2001, 03:02:19)  [GCC 2.96 20000731 (Red Hat Linux 7.1 2 on linux-i386
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> import sys
>>> sys.ps1
'>>> '
>>> sys.ps2
'... '
>>> sys.path
['', '/usr/lib/python1.5/', '/usr/lib/python1.5/plat-linux-i386', '/usr/lib/python1.5/lib-tk', '/usr/lib/python1.5/lib-dynload', '/usr/lib/python1.5/site-packages']
>>>

Or using the "os" module we have:

[root@ftosx1 Python]# python
Python 1.5.2 (#1, Jul  5 2001, 03:02:19)  [GCC 2.96 20000731 (Red Hat Linux 7.1 2 on linux-i386
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> import os
>>> os.environ.get('HOSTNAME')
'ftosx1.futuretg.com'
>>>
 
 

Compiling Python

From the section 6.1.2, in the Python Tutorial we can read, the following statement:

"As an important speed-up of the start-up time for short programs that use a lot of standard modules, if a file called spam.pyc exists in the directory where spam.py is found, this is assumed to contain an already-``byte-compiled'' version of the
module spam. The modification time of the version of spam.py used to create spam.pyc is recorded in spam.pyc, and the .pyc file is ignored if these don't match.

Normally, you don't need to do anything to create the spam.pyc file. Whenever spam.py is successfully compiled, an attempt is made to write the compiled version to spam.pyc. It is not an error if this attempt fails; if for any reason the file is not
written completely, the resulting spam.pyc file will be recognized as invalid and thus ignored later. The contents of the spam.pyc file are platform independent, so a Python module directory can be shared by machines of different architectures."

And therefore we have:

Writing X applications in Python: Tkinter

As explained in the introduction, Python is a universe. However, here we will cover only two small example that make offer an overview about the pyton power.

The first example, is the "Tkinter" module, that produce graphical interface in seconds.

#!/usr/bin/python
from Tkinter import *

root = Tk()

w = Label(root, text="Hello, world!")
w.pack()

root.mainloop()
[root@ftosx1 /root]#

Tcl/Tk is itself an excellent programming language. However, it is possible to get more from it, is we extract and develop a module for the Tk windows.

A simple an effective graphical program 5 lines long, including the "import" line.
 

ZOPE

ZOPE is a Python module to generate and control Websites. The sense is using the Dynamic HTML (DHTML). It is so powerfull that comparable to Microsoft ASP format getting the same results.

ZOPE is a well-designed set of functions, that allow to define and control entire websites.

We here simply introduce it as a extension for the python power.

Conclusions

Python is one of the better programming language ever released. It is so excellent than the millenary PERL may be encapsulated, or any PERL program may be written in Python with better results. (Of course, PERL programmers continues to use PERL).

Python is so excellent that we can build Websites using ZOPE, we can develop installation programs like "anaconda" that uses Tkinter, we can generate graphical Qt applications, using PyQt ... etc.

Simply ... Enjoy Python!

Exercises

  1. Write an example that uses the square root of complex numbers.


Test

  1. Who's the Python inventor?
  2. What is Python ?
  3. What are the two most important python releases ? What is the latest ?
  4. Is possible to write shell script programs in Python ?
  5. What is a ".py" file ? A ".pyc" and a ".pyo" file ?
  6. Are an equivalent to C++ classes supported in Python ?
  7. Would be possible to make arithmetic with complex numbers in python ?
  8. Would be possible to generate HTML files using Python ?
  9. Would python supports "external packages" written by third parts ?
  10. Would be possible to write graphical applications using Qt libraries with Python ?
  11. List three components for the Python Library.
  12. Setup a python list.
  13. Setup a python dictionary.
  14. How we can found the right mode to use the square root, in Python  ?
  15. Is possible to play music with python ?
  16. What are the modules that python load by default ?
  17. What is Tkinter ?
  18. What is ZOPE ?
  19. What is the latest ZOPE release ?
  20. Why we get errors in the following source ?

  21. [root@ftosx1 examples]# python
    Python 1.5.2 (#1, Jul  5 2001, 03:02:19)  [GCC 2.96 20000731 (Red Hat Linux 7.1 2 on linux-i386
    Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
    >>> import cmath
    >>> a=1+1j
    >>> b=sqrt(a)
    Traceback (innermost last):
      File "<stdin>", line 1, in ?
    NameError: sqrt
    >>>
Consult the answers

Check the Interactive Exam Cram Programming: Try the interactive cram ...

Internet Resources for this Chapter.