Using nargs parameter in argparse's add_argument method
I use nargs='' as an add_argument parameter. I specifically used nargs=''nargs='*' as an add_argument parameter. I specifically used nargs='*' to the option to pick defaults if I am not passing any explicit arguments
Including a code snippet as example:
Example: temp_args1.py
Please Note: The below sample code is written in python3. By changing the print statement format, can run in python2
#!/usr/local/bin/python3.6 from argparse import ArgumentParser description = 'testing for passing multiple arguments and to get list of args' parser = ArgumentParser(description=description) parser.add_argument('-i', '--item', action='store', dest='alist', type=str, nargs='*', default=['item1', 'item2', 'item3'], help="Examples: -i item1 item2, -i item3") opts = parser.parse_args() print("List of items: {}".format(opts.alist)) Note: I am collecting multiple string arguments that gets stored in the list - opts.alistopts.alist If you want list of integers, change the type parameter on parser.add_argumentparser.add_argument to intint
Execution Result:
python3.6 temp_agrs1.py -i item5 item6 item7 List of items: ['item5', 'item6', 'item7'] python3.6 temp_agrs1.py -i item10 List of items: ['item10'] python3.6 temp_agrs1.py List of items: ['item1', 'item2', 'item3']