DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Andrew has posted 31 posts at DZone. View Full User Profile

Tea.py

06.22.2007
| 2827 views |
  • submit to reddit
        // Converts long URLs to tiny URLs with URLTea.

#!/usr/bin/env python

__author__="Andrew Pennebaker (andrew.pennebaker@gmail.com)"
__date__="22 Jun 2007"
__copyright__="Copyright 2007 Andrew Pennebaker"
__version__="0.0.1"
__URL__="http://urltea.com/to8"
__credits__="http://tinyurl.com/yswqg3"

import sys, urllib, getopt

CREATE_URL="http://urltea.com/api/text/?url="
COMMENT_DELIMETER="?"

def tiny(url, description=""):
	global CREATE_URL
	global COMMENT_DELIMETER

	try:
		encodedurl=CREATE_URL+urllib.urlencode({"url":url})
		instream=urllib.urlopen(encodedurl)
		tinyurl=instream.read()
		instream.close()

		if len(tinyurl)==0:
			return url

		if len(description)>0:
			tinyurl+=COMMENT_DELIMETER+description

		return tinyurl
	except IOError, e:
		raise "Could not connect."

def usage():
	print "Usage: %s <url1> <url2> <url3> ..." % (sys.argv[0])
	print "-d|--description <comment>"
	print "-h|--help (usage)"

	sys.exit()

def main():
	systemArgs=sys.argv[1:]
	oplist, args=[], []

	comment=""

	try:
		optlist, args=getopt.getopt(systemArgs, "d:h", ["description=", "help"])
	except:
		usage()

	for option, value in optlist:
		if option=="-h" or option=="--help":
			usage()
		elif option=="-d" or option=="--description":
			comment=value

	if len(args)<1:
		usage()

	for u in args:
		print tiny(u, comment)

if __name__=="__main__":
	try:
		main()
	except KeyboardInterrupt, e:
		pass