7.3. What If There Are No Command-Line Parameters?

A weakness in the current module harness is shown up when xgrep is invoked without any command-line parameters.

CD-ROM reference=7014.txt
C>python xgrep.py

Traceback (innermost last):
  File "xgrep.py", line 8, in ?
    XMLGrep (sys.argv[1])
IndexError: list index out of range

The program has trouble accessing the first command-line parameter, which should be at index 1 in the argv list. However, we have not typed in any command-line parameters and therefore there is no entry at offset 1 in the argv list. Python's reaction to this is to raise an exception known as IndexError, and the program terminates.

We will show two ways of gracefully handling this situation.

First, we can check the length of ...

Get XML Processing with Python now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.