rot13.py

#!/usr/bin/python

###
###   Good ol' secure ROT13 encrypter/decrpyter
###

### 
### Version Two is command line driven
### Version Three will be command line driven
### with file input and output
###
import string
import sys 
import getopt

def main():
	try:
		opts, args = getopt.getopt(sys.argv[1:], "hc:f:", ["help", "command", "file"])
		str.join(" ", args)
	except getopt.GetoptError, err:
		print str(err) 
		usage()
		sys.exit(2)
	for o, a in opts:
		if o in ("-h", "--help"):
			usage()
			sys.exit()
		elif o in ("-c", "--command"):
			input = a
			encrypt(input)
			sys.exit(0)
		elif o in ("-f", "--file"):
			input = a
			filerot(input)
			sys.exit(0)
		else:
			usage()
			sys.exit()
	usage()
			

def usage():
	print """First ever python ROT13 encoder/decoder (c)
usage:
   rot13v3.py {-h --help}				Displays me
   rot13v3.py {-c --command} "text to encrypt/decrypt"	Encrypt\decrypt from command line
   rot13v3.py {-f --file} filename			Encrypt\Decrypt file \n"""
	

###
### Encrypt sub 
###    Things to do: Implement file input
### 		     Make it pretty and GUISH
### 		     Copyright the term GUISH
###

def encrypt(input):
	secret = string.maketrans('nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
	output = string.translate(input, secret)
	print ""
	print "\"Secure\" text is:"
	print output
	print ""

### 
###  File Conversion
###

def filerot(input):
	import string
	import shutil
	newfile=input + ".rot"
	input_file = open(input, 'r')
	touched = 0
	secret = string.maketrans('nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')

	shutil.copy (input, newfile)
	try:
		for line in input_file:
			if (touched == 0): # First time around write
				output = string.translate(line, secret)
				output_file = open(newfile, 'w')
				output_file.write(output)
				touched = 1 # Set touched to 1 so from now on it will append
			elif (touched == 1):
				output = string.translate(line, secret)
				output_file = open(newfile, 'a') # Happy file
				output_file.write(output)
			
	finally:
		input_file.close()
	print ""
	print 'Old file was', input + '. New file is ', newfile'
	print ""

###
### Kick her off
###

main()