2015/12/19: Substituting in `pwd`

At least on UNIX-like systems, you tend to build parallel hierarchies: code and tests, code on different branches (for manual comparison), logs of different machines and from different versions (when looking at them manually), etc. Of course, those hierarchies can occur on arbitrary places in the file system hierarchy (e.g., in your home dir, the directory for that very project). A not uncommon operation is to switch from one directory to a corresponding one in a parallel hierarchy.

So the desire is there to simplify this, but having a specialised solution for each use case does not scale. I found the following heuristics work well in practise: substitute the new part of the path into the outermost level such that this results in an existing directory. So, with the script below (called spwd), I can switch to the log of (virtual) node 3 by typing cd `spwd node3`.


#!/usr/bin/env python

## Print the current directory with argv[1] substituted in
## at an appropriate place in the path; here appropriate means
## the uppermost place, such that the resulting directory exists.

import os
import sys

def substpath(path, newpiece):
  """Substitute the new directory at a fitting place.

  """
  components = path.split(os.path.sep)
  for i in range(len(components)):
    newcomponents = components[:]
    newcomponents[i] = newpiece
    newpath = os.path.sep.join(newcomponents)
    if os.path.isdir(newpath):
      return newpath

  return path

if __name__ == "__main__":
  path = os.getcwd()
  if len(sys.argv) < 2:
    print path
  else:
    newpiece = sys.argv[1]
    print substpath(path, newpiece)
download



Cross-referenced by: