code_junkie

How to get/set logical directory path in python

Nov 11th, 2011
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. /real/path/to/dir
  2.  
  3. /linked/path/to/dir
  4.  
  5. >>> import os
  6. >>> os.chdir('/linked/path/to/dir')
  7. >>> print os.getcwd()
  8. /real/path/to/dir
  9.  
  10. import os
  11. from subprocess import Popen, PIPE
  12.  
  13. class CwdKeeper(object):
  14. def __init__(self):
  15. self._cwd = os.environ.get("PWD")
  16. if self._cwd is None: # no environment. fall back to calling pwd on shell
  17. self._cwd = Popen('pwd', stdout=PIPE).communicate()[0].strip()
  18. self._os_getcwd = os.getcwd
  19. self._os_chdir = os.chdir
  20.  
  21. def chdir(self, path):
  22. if not self._cwd:
  23. return self._os_chdir(path)
  24. p = os.path.normpath(os.path.join(self._cwd, path))
  25. result = self._os_chdir(p)
  26. self._cwd = p
  27. os.environ["PWD"] = p
  28. return result
  29.  
  30. def getcwd(self):
  31. if not self._cwd:
  32. return self._os_getcwd()
  33. return self._cwd
  34.  
  35. cwd = CwdKeeper()
  36. print cwd.getcwd()
  37. # use only cwd.chdir and cwd.getcwd from now on.
  38. # monkeypatch os if you want:
  39. os.chdir = cwd.chdir
  40. os.getcwd = cwd.getcwd
  41. # now you can use os.chdir and os.getcwd as normal.
Add Comment
Please, Sign In to add comment