Skip to content

Instantly share code, notes, and snippets.

@greencoder
Last active October 26, 2021 15:27
Show Gist options
  • Save greencoder/729cbe024442e859ab25ec8e06a5cb14 to your computer and use it in GitHub Desktop.
Save greencoder/729cbe024442e859ab25ec8e06a5cb14 to your computer and use it in GitHub Desktop.
Python Argparse Example
import argparse
import pathlib
def valid_dir_arg(value):
""" Used by argparse to determine if the value is a valid directory """
filepath = pathlib.Path(value)
if not filepath.exists() or not filepath.is_dir():
msg = f'Error! This is not a directory: {value}'
raise argparse.ArgumentTypeError(msg)
else:
return filepath
def valid_filepath_arg(value):
filepath = pathlib.Path(value)
if not filepath.exists():
msg = f'File not found: {value}'
raise argparse.ArgumentTypeError(msg)
else:
return filepath
def valid_date_arg(value):
try:
date = arrow.get(value, 'YYYY-MM-DD')
return date
except arrow.parser.ParserError:
msg = 'Invalid date. Must be YYYY-MM-DD format.'
raise argparse.ArgumentTypeError(msg)
if __name__ == '__main__':
# Read command-line arguments
argparser = argparse.ArgumentParser()
argparser.add_argument('src_filepath', type=valid_filepath_arg)
argparser.add_argument('date', type=valid_date_arg)
args = argparser.parse_args()
print(args.src_filepath)
print(args.date)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment