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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.