Created
July 26, 2011 16:38
-
-
Save paulbarbu/1107188 to your computer and use it in GitHub Desktop.
PathValidator
This file contains hidden or 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
class PathValidator(object): | |
'''Class for validating paths | |
It checks whether a file or directory exists at the location pointed by path | |
If the file or directory exists it must be non-empty and readable, | |
else InvalidpathError is raised | |
If the class is instantiated like this: | |
pathsV = PathValidator(True, '/home/path') | |
Then write permissions will be checked, too. | |
Multiple paths can be checked at once too: | |
pathsV = PathValidator(True, '/home/path', '/etc/rc.d') - here write | |
permissions are checked | |
pathsV = PathValidator('/home/path', '/etc/rc.d') - write permissions are | |
not checked | |
''' | |
#TODO think about readable/writeable | |
def __init__(self, writeable = False, *paths): | |
self.paths = [] | |
self.writeable = writeable | |
for path in paths: | |
self.paths.append(path) | |
def validate(self): | |
'''Call various test functions on the paths | |
Tests if the path exists, is non-empty | |
''' | |
import os | |
for path in self.paths: | |
if not os.path.exists(path): | |
raise InvalidPathError(path) | |
elif 0 == os.path.getsize(path): | |
raise InvalidPathError(path) | |
elif not os.access(path, os.R_OK): | |
raise InvalidPathError(path) | |
elif self.writeable and not os.access(path, os.W_OK): | |
raise InvalidPathError(path) | |
class InvalidPathError(Exception): | |
'''Exception raised when an invalid path is found''' | |
def __init__(self, arg): | |
self.args = arg; | |
def __str__(self): | |
return 'Invalid path: {0}'.format(''.join(self.args)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment