Created
August 24, 2012 15:27
-
-
Save lsbardel/3451986 to your computer and use it in GitHub Desktop.
Python Path
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import sys | |
if sys.version_info > (3,0): | |
string_type = str | |
else: | |
string_type = unicode | |
range = xrange | |
class Path(string_type): | |
def __new__(cls, path = None): | |
path = path or '' | |
abspath = os.path.abspath(path) | |
return super(Path,cls).__new__(cls, abspath) | |
@classmethod | |
def cwd(cls): | |
'''Return the current working directory as a path object.''' | |
return cls(os.getcwd()) | |
isfile = lambda self: os.path.isfile(self) | |
isdir = lambda self: os.path.isdir(self) | |
exists = lambda self: os.path.exists(self) | |
realpath = lambda self: self.__class__(os.path.realpath(string_type(self))) | |
def join(self, *path): | |
return self.__class__(os.path.join(self, *path)) | |
def split(self): | |
d,f = os.path.split(self) | |
return self.__class__(d),f | |
def dir(self): | |
if self.isfile(): | |
return self.parent | |
elif self.isdir(): | |
return self | |
else: | |
raise ValueError('{0} not a valid directory'.format(self)) | |
@property | |
def parent(self): | |
return self.__class__(os.path.dirname(self)) | |
def ancestor(self, n): | |
p = self | |
for i in range(n): | |
p = p.parent | |
return p | |
def add2python(self, module = None, up = 0, down = None, front = False, | |
must_exist = True): | |
if module: | |
try: | |
__import__(module) | |
return module | |
except ImportError: | |
pass | |
dir = self.dir().ancestor(up) | |
if down: | |
dir = dir.join(*down) | |
added = False | |
if dir.isdir(): | |
if dir not in sys.path: | |
if front: | |
sys.path.insert(0,dir) | |
else: | |
sys.path.append(dir) | |
added = True | |
else: | |
raise ValueError('Directory {0} not available'.format(dir)) | |
if module: | |
try: | |
__import__(module) | |
return module | |
except ImportError: | |
if must_exist: | |
raise | |
return added |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment