Chapter 10. Brief Tour of the Standard Library 80 Python Tutorial, Release 3.9.5 10.3 Command Line Arguments 10.5 String Pattern Matching 10.4 Error Output Redirection and Program Termination 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: 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: 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']}$ . 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: The most direct way to terminate a script is to use$_{sys.exit()}$ . The$_{re}$ module provides regular expression tools for advanced string processing. For complex matching and manip- ulation, regular expressions offer succinct, optimized solutions: When only simple capabilities are needed, string methods are preferred because they are easier to read and debug: >>> 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' >>> 'tea for too'.replace( 'too','two') 'tea for two' >>> sys.stderr.write('Warning, log file not found starting a new one ') Warning, log file not found starting a new one 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) >>> import sys >>> print(sys.argv) ['demo.py', 'one', 'two', 'three']