#! /usr/bin/env python import commands, os, re from optparse import OptionParser ## Read command line opts parser = OptionParser() parser.add_option("-l", "--maxlength", dest="maxlength", help="set max path length to MAXLENGTH", metavar="MAXLENGTH") parser.add_option("-s", "--step", dest="step", help="try increasing MAXLENGTH in units of STEP to get an acceptable short path", metavar="STEP") (options, args) = parser.parse_args() ## Set max length of path string MAXLENGTH = 15 if options.maxlength != None: MAXLENGTH = int(options.maxlength) STEP = 5 if options.step != None: STEP = int(options.step) ## Get path and handle stale file handle error path = commands.getoutput("pwd") if re.search("pwd:\s+error", path) != None: print "...", else: ## Do HOME -> ~ substitution shortpath = re.sub(os.environ["HOME"], "~", path) ## Truncate the subst path to match the MAXLENGTH param ## If it won't work, increase MAXLENGTH by STEP and try again recursively pathlen = len(shortpath) if len(shortpath) > MAXLENGTH: subpathlen1, subpathlen2 = 0, 0 while subpathlen2 == 0: while subpathlen1 < MAXLENGTH: subpathlen2 = subpathlen1 subpathlen1 = pathlen - shortpath[:pathlen-subpathlen1].rfind('/') #print MAXLENGTH, subpathlen2 MAXLENGTH = MAXLENGTH + STEP ## Obtain the shortened path (NB. subpathlen > 0) if shortpath[0] == "~": shortpath = "~/..." + shortpath[-subpathlen2:] else: shortpath = "..." + shortpath[-subpathlen2:] print shortpath