#! /usr/bin/env python """Encodes and decode text via Caesar (rot13) rotation. This program filters text through rot13 translation. Typically it reads text from standard input and writes to standard output. With the -f option, it will read input from the file, but still writes to standard output. Usage: %(program)s [-f file] [-h] Where: --help -h - print this message file - optional file name to read, otherwise standard input is read. """ import sys import string import getopt program = sys.argv[0] def usage(status, msg=''): stdout = sys.stdout try: sys.stdout = sys.stderr if msg: print msg print __doc__ % globals() finally: sys.stdout = stdout sys.exit(status) def main(): table = string.maketrans( 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') try: opts, args = getopt.getopt(sys.argv[1:], 'hf:', ['file=', 'help']) except getopt.error, msg: usage(1, msg) # default values help = 0 file = None for opt, arg in opts: if opt in ('-h', '--help'): help = 1 elif opt in ('-f', '--file'): file = arg # sanity checks if args: usage(1) if help: usage(0) if file: try: fp = open(file, 'r') text = fp.read() fp.close() except IOError, (errno, msg): print '%s: %s' % (msg, file) sys.exit(1) else: text = sys.stdin.read() print string.translate(text, table) if __name__ == '__main__': main()