directory path with python argparse

38

import os
import argparse
from datetime import datetime


def parse_arguments():
    parser = argparse.ArgumentParser(description='Process command line arguments.')
    parser.add_argument('-path', type=dir_path)
    parser.add_argument('-e', '--yearly', nargs = '*', help='yearly date', type=date_year)
    parser.add_argument('-a', '--monthly', nargs = '*',help='monthly date', type=date_month)

    return parser.parse_args()


def dir_path(path):
    if os.path.isdir(path):
        return path
    else:
        raise argparse.ArgumentTypeError(f"readable_dir:{path} is not a valid path")


def date_year(date):
    if not date:
        return

    try:
        return datetime.strptime(date, '%Y')
    except ValueError:
        raise argparse.ArgumentTypeError(f"Given Date({date}) not valid")


def date_month(date):
    if not date:
        return

    try:
        return datetime.strptime(date, '%Y/%m')
    except ValueError:
        raise argparse.ArgumentTypeError(f"Given Date({date}) not valid")


def main():
    parsed_args = parse_arguments()

if __name__ == "__main__":
main()

Comments

Submit
0 Comments