## 10.3 Command Line Arguments 

Common utility scripts often need to process command line arguments. These arguments are stored in the sys module’s argv attribute as a list. For instance the following output results from running python demo.py one $_{two three}$at the command line: 

>>> import sys >>> print(sys.argv) ['demo.py', 'one', 'two', 'three'] 

The argparse module provides a more sophisticated mechanism to process command line arguments. The fol- lowing script extracts one or more filenames and an optional number of lines to be displayed: 

import argparse parser =argparse.ArgumentParser(prog='top', description ='Show top lines from each file') parser.add_argument( 'filenames', nargs ='+') parser.add_argument( '-l ','--lines ',type=int, default =10 ) args =parser.parse_args() print(args) 

When run at the command line with$_{python top.py --lines=5 alpha.txt beta.txt}$ , the script sets args.lines to$_{5}$and$_{args.filenames}$ to$_{['alpha.txt', 'beta.txt']}$ . 

## 10.4 Error Output Redirection and Program Termination 

The$_{sys}$ module also has attributes for stdin , stdout , and stderr . The latter is useful for emitting warnings and error messages to make them visible even when stdout has been redirected: 

>>> sys.stderr.write('Warning, log file not found starting a new one 
 ') Warning, log file not found starting a new one 

The most direct way to terminate a script is to use$_{sys.exit()}$ . 

## 10.5 String Pattern Matching 

The$_{re}$ module provides regular expression tools for advanced string processing. For complex matching and manip- ulation, regular expressions offer succinct, optimized solutions: 

>>> import re >>> re.findall( r'\bf[a-z]* ','which foot or hand fell fastest') ['foot', 'fell', 'fastest'] >>> re.sub(r'(\b[a-z]+)\1',r'\1','cat in the the hat ') 'cat in the hat' 

When only simple capabilities are needed, string methods are preferred because they are easier to read and debug: 

>>> 'tea for too'.replace( 'too','two') 'tea for two' 

