How to use *args with argparse?
I’m trying to use argparse module to parse command-line arguments, and I would like to use *args as the number of arguments is not fixed.
My code:
if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("program", help='Name of the program') parser.add_argument("type", help='Type of program') parser.add_argument("date", help='Date of the file')
These 3 arguments are a must: program, type and date. However, the next arguments are optional (sometime required, sometime not). So, I thought of using *args for the other arguments, but I’m unsure how that’s done using argsparse.
The optional arguments would look like:
if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("program", help='Name of the program') parser.add_argument("type", help='Type of program') parser.add_argument("date", help='Date of the file') #below arguments are optinal. Hence, I may need to pass all of them in one scenario, or just 1-2 in another scenario. parser.add_argument("option1", help='optinal 1') parser.add_argument("option2", help='optinal 2') parser.add_argument("option3", help='optinal 3') parser.add_argument("option4", help='optinal 4')
Please help. Thanks in advance.
Use keyword required=bool
parser = argparse.ArgumentParser() parser.add_argument("-p","--program", help='Name of the program', required=True) parser.add_argument("-f", "--foo", help='Foo', required=False)