Last active
November 11, 2023 22:34
-
-
Save Tatsh/cc7e7217ae21745eb181 to your computer and use it in GitHub Desktop.
Check if a directory argument is writeable or readable.
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
from os.path import isdir, realpath | |
import argparse | |
import os | |
class ReadableDirectoryAction(argparse.Action): | |
def __call__(self, parser, namespace, values, option_string=None): | |
prospective_dir = values | |
if not isdir(prospective_dir): | |
raise argparse.ArgumentTypeError('%s is not a valid directory' % ( | |
prospective_dir, | |
)) | |
if os.access(prospective_dir, os.R_OK): | |
setattr(namespace, self.dest, realpath(prospective_dir)) | |
return | |
raise argparse.ArgumentTypeError('%s is not a readable directory' % ( | |
prospective_dir, | |
)) | |
class WritableDirectoryAction(argparse.Action): | |
def __call__(self, parser, namespace, values, option_string=None): | |
prospective_dir = values | |
if not isdir(prospective_dir): | |
raise argparse.ArgumentTypeError('%s is not a valid directory' % ( | |
prospective_dir, | |
)) | |
if os.access(prospective_dir, os.W_OK): | |
setattr(namespace, self.dest, realpath(prospective_dir)) | |
return | |
raise argparse.ArgumentTypeError('%s is not a readable directory' % ( | |
prospective_dir, | |
)) | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser() | |
parser.add_argument('search_path', | |
metavar='SEARCH_PATH', | |
action=ReadableDirectoryAction) | |
parser.add_argument('out_dir', | |
metavar='OUT_DIR', | |
action=WritableDirectoryAction) | |
parser.add_argument('-v', | |
'--verbose', | |
action='store_true') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There is a typo in the WritableDirectoryAction:
'%s is not a readable directory'
should be'%s is not a writeable directory'