5

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 say reports.txt

Now I want to add this functionality to allow users to choose what to put the filename and where to save as so

python main.py -d -o output/newfilname -i listhere/users.txt

Everything is same but I want another argument -o to be passed which will determine the filpath and name to be saved. How do I do it. What is the best way to handle or combine multiple options.

I tried this

    parser = argparse.ArgumentParser(description = "CHECK-ACCESS REPORTING.")
    parser.add_argument('--user','-d', nargs='?')
    parser.add_argument('--output','-d -o', nargs='?')
    parser.add_argument('--input','-i', nargs='?')
    args = parser.parse_args(sys.argv[1:])

   if args.output and args.input:
        #operation that involves output filename too
   elif args.user and not args.input:
       #default operation only
   else:
      #notset

I am getting this error when trying to solve the issue this way

Error:

report.py: error: unrecognized arguments: -o listhere/users.txt

6
  • You can't attach more - options to another - option, no, -d -o is not a valid option name here. Why not just have a -o option to specify the output name? Commented Jun 25, 2017 at 10:52
  • remove -d and it will work Commented Jun 25, 2017 at 10:53
  • Why I did that is if I don't pass some values after -d it wont work . How to make -d as just the parameter without value. Tried appending default='' to -d but not working Commented Jun 25, 2017 at 11:04
  • if i print the value of arg with this parameter i get nothing python report.py -d -o listhere/users.txt -i list/here.txt Commented Jun 25, 2017 at 11:07
  • What's the difference between the old -d users.txt and the new -i users.txt? What's the purpose of option -d? Commented Jun 25, 2017 at 11:11

2 Answers 2

5

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')
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks very descriptive I was very much unclear about default ,const
Another thought: -d -o is split into 2 strings by the bash; sometimes it helps to look at sys.argv to seek what argparse has to work with.
can you consider this please python testing.py -d -i somevalue -o somevalue I dont want to pass value after -d which result in not satisfying the condition if args.users: if args.input and args.output
Ok did it by setting the const="some value"
0

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

2 Comments

The problem there is you have to pass some value after -d flags I just want to pass the flag -d without any value to it
@TaraPrasadGurung The order of the options does not matter, e.g.: -o output.txt -i input.txt -d. Option -d does not have any value on the command line. If the option is used somewhere on the command line, then it sets variable discrepancy to true.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.