5 # Retrieved from http://code.activestate.com/recipes/302594/
10 def relpath(target, base=os.curdir):
12 Return a relative path to the target from either the current dir or an optional base dir.
13 Base can be a directory specified either as absolute or relative to current dir.
16 if not os.path.exists(target):
17 raise OSError, 'Target does not exist: '+target
19 if not os.path.isdir(base):
20 raise OSError, 'Base is not a directory or does not exist: '+base
22 base_list = (os.path.abspath(base)).split(os.sep)
23 target_list = (os.path.abspath(target)).split(os.sep)
25 # On the windows platform the target may be on a completely different drive from the base.
26 if os.name in ['nt','dos','os2'] and base_list[0] <> target_list[0]:
27 raise OSError, 'Target is on a different drive to base. Target: '+target_list[0].upper()+', base: '+base_list[0].upper()
29 # Starting from the filepath root, work out how much of the filepath is
30 # shared by base and target.
31 for i in range(min(len(base_list), len(target_list))):
32 if base_list[i] <> target_list[i]: break
34 # If we broke out of the loop, i is pointing to the first differing path elements.
35 # If we didn't break out of the loop, i is pointing to identical path elements.
36 # Increment i so that in all cases it points to the first differing path elements.
39 rel_list = [os.pardir] * (len(base_list)-i) + target_list[i:]
40 if (len(rel_list) == 0):
42 return os.path.join(*rel_list)
44 if __name__ == "__main__":
45 print(relpath(sys.argv[1], sys.argv[2]))