Changeset 36:f6e3e798fa2a in misc for tictac.py


Ignore:
Timestamp:
09/02/07 00:29:48 (5 years ago)
Author:
Eriol
Branch:
misc
Convert:
svn:e60e002c-0983-44b9-b2ae-8842d539f768/misc@39
Message:

Added interactive mode

File:
1 edited

Legend:

Unmodified
Added
Removed
  • tictac.py

    r35 r36  
    2424## 
    2525 
     26import atexit 
    2627import os.path 
     28import StringIO 
    2729 
    2830from optparse import OptionParser 
    29 from sys import stdout 
     31from sys import stdin, stdout 
    3032 
    3133def backread(afile, buffer_size=1024): 
     
    4547        yield ''.join(reversed(data)) 
    4648 
     49def _print(data): 
     50    for l in backread(data): 
     51        stdout.write(l) 
     52    stdout.write('\n') 
     53 
    4754def main(): 
    48     usage = 'usage: %prog file' 
     55    interactive = False 
     56    data = StringIO.StringIO() 
     57    usage = '''usage: %prog [FILE] 
     58 
     59    With no FILE read standard input 
     60''' 
    4961    parser = OptionParser(usage) 
    5062    (options, args) = parser.parse_args() 
    5163 
    52     if len(args) != 1: 
    53         parser.error('Incorrect number of arguments') 
     64    if len(args) < 1: 
     65        interactive = True 
    5466    elif not os.path.isfile(args[0]): 
    5567        parser.error('No such file') 
    5668 
    57     fin = open(args[0], 'r') 
    58     try: 
    59         for l in backread(fin): 
    60             stdout.write(l) 
    61         stdout.write('\n') 
    62     finally: 
    63         fin.close() 
     69    if interactive: 
     70        while True: 
     71            line = stdin.readline() 
     72            if not line: break 
     73            data.write(line) 
     74        atexit.register(_print, data) 
     75    else: 
     76        fin = open(args[0], 'r') 
     77        try: 
     78            _print(fin) 
     79        finally: 
     80            fin.close() 
    6481 
    6582if __name__ == '__main__': 
Note: See TracChangeset for help on using the changeset viewer.