Skip to content

Instantly share code, notes, and snippets.

@Tatsh
Last active November 11, 2023 22:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Tatsh/cc7e7217ae21745eb181 to your computer and use it in GitHub Desktop.
Save Tatsh/cc7e7217ae21745eb181 to your computer and use it in GitHub Desktop.
Check if a directory argument is writeable or readable.
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')
@Roang-zero1
Copy link

Roang-zero1 commented Jun 8, 2019

There is a typo in the WritableDirectoryAction: '%s is not a readable directory' should be '%s is not a writeable directory'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment