0

I have below python program takes argument from command line.

import argparse
import sys

choice=['orange','apple', 'grapes', 'banna']

def select():
    parser = argparse.ArgumentParser(prog='one', description='name test')
    parser.add_argument(
        'fname',
        action="store",
        type=str,
        choices=choice,
        help="furits name")

    args = parser.parse_args(sys.argv[1:2])

    print 'selected name {0}\n'.format(args.fname)

if __name__ == '__main__':
    select()

this works

 python s.py apple
selected name apple

How can inline argument with-in main function. I tried this but its not working.

change main line this.

if __name__ == '__main__':
    sys.argv[0]='apple'
    select()

getting below error.

usage: one [-h] {orange,apple,grapes,banna}
one: error: too few arguments

How can I achieve this in argument?

thanks -SR

1
  • The default action for parse_args is to use sys.argv[1:]. sys.argv[0] is used as the default prog attribute. Commented Nov 3, 2017 at 22:32

1 Answer 1

1

Your index is wrong sys.argv[0] will be the path of the python script. What you want is:

if __name__ == '__main__':
    if len(sys.argv) == 1:
        sys.argv.append("apple")
    select()

But, this is a weird way of doing things. After a bit more thought, this occurred to me:

choice=['orange','apple', 'grapes', 'banna']

def select():
    parser = argparse.ArgumentParser(prog='one', description='name test')
    parser.add_argument(
        'fname',
        nargs='?',
        default='apple',
        action="store",
        type=str,
        choices=choice,
        help="furits name")

    args = parser.parse_args(sys.argv[1:2])

    print 'selected name {0}\n'.format(args.fname)

if __name__ == '__main__':
    select()

Note the nargs='?' and default='apple' additions to the call to add_argument(). These make the parameter optional and set the default value to "apple" if no argument is supplied.

Sign up to request clarification or add additional context in comments.

2 Comments

@BogdanMarginean you are correct, my testing was poor, corrected.
@sfgroups No problem

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.