filter.py

Download filter.py

 1: #!/usr/bin/python3
 2: """ Sample generic filter command, written in Python.  A "filter"
 3:     should process each filename argument, or stdin if no arguments
 4:     are given.  A "-" for a filename means stdin.
 5: 
 6:     This script prints a header line, then the file's contents,
 7:     and then a footer line.  Any line containing a plus symbol
 8:     is converted to uppercase, just for laughs.
 9: 
10:     Written 4/2014 by Wayne Pollock, Tampa Florida USA
11: """
12: 
13: import re, sys
14: 
15: def main ():
16:    # Check if any command-line args were given;
17:    # if not, use "-" (Standard Input):
18:    if len( sys.argv[1:] ) == 0:
19:      sys.argv.insert( 1, '-' )
20: 
21:    # Process each filename on the command line:
22:    for filename in sys.argv[1:]:
23:       process( filename )
24:       print()  # Print a blank line, as a separator.
25: 
26: # Do something interesting for a given file:
27: def process ( filename ):
28: 
29:    # If the argument is "-", use Standard Input instead:
30:    if filename == '-':
31:      filename = "STDIN"  # A more useful name than "-".
32:      file = sys.stdin
33:    else:
34:       file = open( filename )
35: 
36:    # This part is done once per file:
37:    print( "file prolog: filename: " + filename )
38: 
39:    # This is done for each line in the file:
40:    for line in file:
41:       if re.search( "\+", line ):  # find lines containing a "+"
42:          line = line.upper()
43:       print( line, end="" )
44: 
45:    # This part is done once per file:
46:    print( "file epilogue: The end" )
47: 
48:    # Close the file, except if standard input; otherwise,
49:    # a second "-" as a command line arg will fail:
50:    if file != sys.stdin:
51:       file.close()
52: 
53: # This standard line allows this file to be imported or run directly:
54: if __name__ == "__main__": main()