Skip to content Skip to sidebar Skip to footer

How To Add Multiple Argument Options In Python Using Argparse?

My Requirement: For now when I run my python application with this command python main.py -d listhere/users.txt The program will run and save the result file as predefined name s

Solution 1:

A nargs='?' flagged option works in 3 ways

parser.add_argument('-d', nargs='?', default='DEF', const='CONST')

commandline:

foo.py -d value # => args.d == 'value'
foo.py -d       # => args.d == 'CONST'
foo.py          # => args.d == 'DEF'

https://docs.python.org/3/library/argparse.html#const

Taking advantage of that, you shouldn't need anything like this erroneous -d -o flag.

If you don't use the const parameter, don't use '?'

parser.add_argument('--user','-u', nargs='?', const='CONST', default='default_user')
parser.add_argument('--output','-o', default='default_outfile')
parser.add_argument('--input','-i', default='default_infile')

Solution 2:

Do you want to have something like this:

import argparse

def main():
    parser = argparse.ArgumentParser(
        description='Check-Access Reporting.',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )
    parser.add_argument(
        '-d',
        dest='discrepancy',
        action='store_true',
        help='Generate discrepancy report.',
    )
    parser.add_argument(
        '--input',
        '-i',
        default='users.txt',
        help='Input file for the report.',
    )
    parser.add_argument(
        '--output',
        '-o',
        default='reports.txt',
        help='Output file for the report.',
    )
    args = parser.parse_args()

    if args.discrepancy:
        print('Report type: {}'.format(args.report_type))
        print('Input file: {}'.format(args.input))
        print('Output file: {}'.format(args.output))
    else:
        print('Report type is not specified.')

if __name__ == '__main__':
    main()

Result of option --help:

usage: ptest_047.py [-h] [-d] [--input INPUT] [--output OUTPUT]

Check-Access Reporting.

optional arguments:
  -h, --help            show this help message and exit
  -d                    generate discrepancy report (default: False)
  --input INPUT, -i INPUT
                        input file for the report (default: users.txt)
  --output OUTPUT, -o OUTPUT
                        output file for the report (default: reports.txt)

Without any option (or missing option -d):

Report type is not specified.

With option -d:

Report type: discrepancy
Input file: users.txt
Output file: reports.txt

With -d --input input.txt --output output.txt:

Report type: discrepancy
Input file: input.txt
Output file: output.txt

Post a Comment for "How To Add Multiple Argument Options In Python Using Argparse?"