4 from __future__ import with_statement
13 @contextlib.contextmanager
14 def change_directory(directory):
15 previousDirectory = os.getcwd()
17 currentDirectory = os.getcwd()
20 yield previousDirectory, currentDirectory
22 os.chdir(previousDirectory)
25 @contextlib.contextmanager
26 def pickled(filename):
28 Here is an example usage:
29 with pickled("foo.db") as p:
30 p("users", list).append(["srid", "passwd", 23])
33 if os.path.isfile(filename):
34 data = pickle.load(open(filename))
38 def getter(item, factory):
42 data[item] = factory()
47 pickle.dump(data, open(filename, "w"))
50 @contextlib.contextmanager
51 def redirect(object_, attr, value):
54 ... with redirect(sys, 'stdout', open('stdout', 'w')):
57 >>> print "we're back"
60 orig = getattr(object_, attr)
61 setattr(object_, attr, value)
65 setattr(object_, attr, orig)
70 >>> pathsplit("/a/b/c")
72 >>> pathsplit("./plugins/builtins.ini")
73 ['.', 'plugins', 'builtins.ini']
75 pathParts = path.split(os.path.sep)
79 def commonpath(l1, l2, common=None):
81 >>> commonpath(pathsplit('/a/b/c/d'), pathsplit('/a/b/c1/d1'))
82 (['', 'a', 'b'], ['c', 'd'], ['c1', 'd1'])
83 >>> commonpath(pathsplit("./plugins/"), pathsplit("./plugins/builtins.ini"))
84 (['.', 'plugins'], [''], ['builtins.ini'])
85 >>> commonpath(pathsplit("./plugins/builtins"), pathsplit("./plugins"))
86 (['.', 'plugins'], ['builtins'], [])
94 for i, (leftDir, rightDir) in enumerate(zip(l1, l2)):
95 if leftDir != rightDir:
96 return l1[0:i], l1[i:], l2[i:]
98 if leftDir == rightDir:
100 return l1[0:i], l1[i:], l2[i:]
105 >>> relpath('/', '/')
107 >>> relpath('/a/b/c/d', '/')
109 >>> relpath('/a/b/c/d', '/a/b/c1/d1')
111 >>> relpath('/a/b/c/d', '/a/b/c1/d1/')
113 >>> relpath("./plugins/builtins", "./plugins")
115 >>> relpath("./plugins/", "./plugins/builtins.ini")
118 sourcePath = os.path.normpath(p1)
119 destPath = os.path.normpath(p2)
121 (common, sourceOnly, destOnly) = commonpath(pathsplit(sourcePath), pathsplit(destPath))
122 if len(sourceOnly) or len(destOnly):
123 relParts = itertools.chain(
124 (('..' + os.sep) * len(sourceOnly), ),
127 return os.path.join(*relParts)