Argument Parser(argparse) Examples : Different type of arguments with custom handlers added. For PATH you can pass "-path" followed by path value as argument
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()
add_argumentdoes not take aoptionparameter. Is this path name supposed to come from the command line? Is it ok to change path after parsing?