Last active
November 4, 2021 16:55
-
-
Save greencoder/49eef6b8eebcba353c62cf9de3c13bfc to your computer and use it in GitHub Desktop.
Argparse Example with Date and Directory Validation
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
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