Skip to content

Instantly share code, notes, and snippets.

@greencoder
Last active November 4, 2021 16:55
Show Gist options
  • Save greencoder/49eef6b8eebcba353c62cf9de3c13bfc to your computer and use it in GitHub Desktop.
Save greencoder/49eef6b8eebcba353c62cf9de3c13bfc to your computer and use it in GitHub Desktop.
Argparse Example with Date and Directory Validation
import argparse
import arrow
import pathlib
def valid_date_arg(value):
""" Used by argparser to validate date arguments """
try:
return arrow.get(value, 'YYYY-MM-DD')
except arrow.parser.ParserError:
msg = f'Not a valid date in YYYY-MM-DD format: "{value}"'
raise argparse.ArgumentTypeError(msg)
def valid_filepath_arg(value):
""" Used by argparse to see if a file exists """
filepath = pathlib.Path(value)
if not filepath.exists():
msg = f'File "{arg}" does not exist'
raise argparse.ArgumentTypeError(msg)
else:
return filepath
def valid_dir_arg(value):
""" Used by argparse to see if a directory exists """
filepath = pathlib.Path(value)
if not filepath.exists() or not filepath.is_dir():
msg = f'Directory "{arg}" does not exist'
raise argparse.ArgumentTypeError(msg)
else:
return filepath
# Read command-line arguments
argparser = argparse.ArgumentParser()
argparser.add_argument('date', type=valid_date_arg)
argparser.add_argument('directory', type=valid_dir_arg)
args = argparser.parse_args()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment