Last active
October 26, 2021 15:27
-
-
Save greencoder/729cbe024442e859ab25ec8e06a5cb14 to your computer and use it in GitHub Desktop.
Python Argparse Example
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 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