zvodd
8/3/2014 - 3:33 PM

Simple Example Command Line Python App

Simple Example Command Line Python App

#!/usr/bin/env python
import sys

def main():
	if len(sys.argv) >= 2:
		infile = sys.argv[1]
	else:
		infile = sys.stdin

	if len(sys.argv) >= 3:
		outfile = sys.argv[2]
	else:
		outfile = sys.stdout

	try:
		if type(infile) == file:
			infh = infile
		else:
			infh = open(infile,'r')
		data = infh.read()
		infh.close()
	except IOError:
		exit("Failed to open file for %r reading" % infile)

	try: 
		if type(outfile) == file:
			outfh = outfile
		else:
			outfh =  open(outfile,'w')

		for count,char in enumerate(data):
			seperator = ' '
			if count % 8 == 7 :
				seperator = '\n'
			outfh.write("{0:08b}{1}".format(ord(char), seperator))
		outfh.close()
	except IOError:
		exit("Failed to open file for %r writing" % outfile)

if __name__ == "__main__":
	main()