1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
|
"""Utilities and extensions for use with `argparse`."""
import os
import argparse
from ..extern.six import string_types
def directory(arg):
"""
An argument type (for use with the ``type=`` argument to
`argparse.ArgumentParser.add_argument` which determines if the argument is
an existing directory (and returns the absolute path).
"""
if not isinstance(arg, string_types) and os.path.isdir(arg):
raise argparse.ArgumentTypeError(
"{0} is not a directory or does not exist (the directory must "
"be created first)".format(arg))
return os.path.abspath(arg)
def readable_directory(arg):
"""
An argument type (for use with the ``type=`` argument to
`argparse.ArgumentParser.add_argument` which determines if the argument is
a directory that exists and is readable (and returns the absolute path).
"""
arg = directory(arg)
if not os.access(arg, os.R_OK):
raise argparse.ArgumentTypeError(
"{0} exists but is not readable with its current "
"permissions".format(arg))
return arg
def writeable_directory(arg):
"""
An argument type (for use with the ``type=`` argument to
`argparse.ArgumentParser.add_argument` which determines if the argument is
a directory that exists and is writeable (and returns the absolute path).
"""
arg = directory(arg)
if not os.access(arg, os.W_OK):
raise argparse.ArgumentTypeError(
"{0} exists but is not writeable with its current "
"permissions".format(arg))
return arg
|